Synchronized method does not work as expected

后端 未结 5 1572
广开言路
广开言路 2020-12-18 09:26

I have a variable which is shared by two threads. The two threads will do some operations on it. I don\'t know why the result of sharedVar is different every time I execute

5条回答
  •  既然无缘
    2020-12-18 10:07

    Join the thread immediately after start method. From this thread-1 will start and go to dead state after that thread-2 will start and go to dead state. So it will print your expected output always.

    Change the code as shown below:-

    public class Main{
    
        public static int sharedVar = 0;
    
        public static void main(String[] args)
    
            {
                MyThread mt1 = new MyThread();
                MyThread mt2 = new MyThread();
    
                try
    
                    {
                        mt1.start();
                        mt1.join();
                        mt2.start();
                        mt2.join();
                    }
    
                catch (InterruptedException e1)
    
                    {
                        e1.printStackTrace();
                    }
    
                System.out.println(sharedVar);
    
            }
    }
    
    class MyThread extends Thread
    {
        private int times = 1000000;
    
        private synchronized void addOne()
            {
                for (int i = 0; i < times; ++i)
                    {
                        Main.sharedVar++;
                    }
            }
    
        @Override
        public void run()
            {
                addOne();
            }
    }
    

提交回复
热议问题