簡體   English   中英

Java中的線程和同步

[英]Threads and Synchronization in java

考慮以下代碼以了解線程同步方法和同步塊

public class ThreadSynchronizationPartI {
    public static int myValue=1;
    public static void main(String [] args)
    {
        Thread t=new Thread(()->
        {
            while(true)
            {
            updateBalance();
                }
        });
        t.start();

        t=new Thread(()->{
        while(true)
        {
            monitorBalance();
        }
        });
        t.start();
    }
    public static synchronized void updateBalance(){
        System.out.println("start "+myValue);
         myValue = myValue + 1;
        //    myValue = myValue - 1;
        System.out.println("end "+myValue);

    }
    public static synchronized void monitorBalance(){
        int b=myValue;
        if(b>1)
        {
            System.out.println("B is greater than 1 by"+(b-1));
            System.exit(1);
        }
    }
}

為什么給出以下輸出:開始1結束2開始2結束3開始3結束4開始4結束5開始5結束6開始6結束7開始7結束8 B大於1乘7

誰能解釋?

您的程序將從main()開始執行。 最初,myValue的值為1,然后將創建一個新線程t。 在條件成立之前,將執行while循環。 當控件到達updateBalance()時,它將跳轉到該方法,並且println()將打印myValue的值為1。因此輸出為: start 1 ,然后將myValue的值增大為+1,然后結果,下一個println()會將輸出打印為: end 2 當while循環中下一個線程的條件為true時,控制權將在那里轉移。 將調用monitorBalance()並將b初始化為myValue的值。 當條件b>1計算為true時,將打印: B is greater than 1 by (b-1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM