简体   繁体   English

Java中的线程和同步

[英]Threads and Synchronization in java

Consider the below code for Thread Synchronization Method and a Synchronization Block 考虑以下代码以了解线程同步方法和同步块

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);
        }
    }
}

Why Does it give the following output: start 1 end 2 start 2 end 3 start 3 end 4 start 4 end 5 start 5 end 6 start 6 end 7 start 7 end 8 B is greater than 1 by 7 为什么给出以下输出:开始1结束2开始2结束3开始3结束4开始4结束5开始5结束6开始6结束7开始7结束8 B大于1乘7

Can anyone explain? 谁能解释?

The execution of your program will start from main(). 您的程序将从main()开始执行。 Initially the value of myValue is 1 and a new thread t will be created. 最初,myValue的值为1,然后将创建一个新线程t。 Until the condition is true the while loop will be executed. 在条件成立之前,将执行while循环。 When the control will reach updateBalance(), it will jump to that method and the println() will print the value of myValue which is 1. Hence the output will be : start 1 it will then increase the value of myValue to +1 and as a result the next println() would print the output as : end 2 . 当控件到达updateBalance()时,它将跳转到该方法,并且println()将打印myValue的值为1。因此输出为: start 1 ,然后将myValue的值增大为+1,然后结果,下一个println()会将输出打印为: end 2 When the condition for next thread will be true in while loop, the control will be transferred there. 当while循环中下一个线程的条件为true时,控制权将在那里转移。 The monitorBalance() will be called and b is initialized the value of myValue. 将调用monitorBalance()并将b初始化为myValue的值。 When the condition b>1 evaluates to true it will print : B is greater than 1 by (b-1) . 当条件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