Java synchronized method does not work as expected

雨燕双飞 提交于 2019-12-08 04:26:58

问题


I did some research but I couldn't find right answer I guess.

public class MultiThreadTwo
{
    private int count = 0;
    public synchronized void increment() // I synchronized it here
    {
        count++;
    }
    public static void main (String [] args)
    {
        MultiThreadTwo app = new MultiThreadTwo();
        app.doWork();
    }
    public void doWork()
    {
        Thread t1 = new Thread(new Runnable() {
            public void run(){
                for (int i=0;i<100;i++ )
                    {
                        increment(); // increments
                    }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            public void run()
            {
                for (int i=0;i<100;i++ )
                    {
                        increment(); // increments
                    }
            }
        });

        t1.start();
        t2.start();

        System.out.println("Count is : "+count);

        try
        {
            t1.join(); // wait for completes
            t2.join(); // wait for completes
        }catch(InterruptedException e)
        {
            e.printStackTrace();
        } 
    }
}

My output always diffrent like 200,182,171,65,140. How can I fix this I know I can check the value of count and if it is not the value I expected I can call the run again and again but It doesn't help me at all. synchronized keyword shouldn't fix that situation ?

What am I missing ?

Solution : Printing count after join fixed my problem.


回答1:


If you join the threads before priniting the result and make count volatile, you will always get 200.

Eventhough volatile does not harm here, it is not necessary. The accesses to count from t1 and t2 work properly because increment method is synchronized on the same object and calling join on a thread creates a happens-before relationship. Thus, the main thread is guaranteed to see a correct value of count even without volatile, too.



来源:https://stackoverflow.com/questions/26872241/java-synchronized-method-does-not-work-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!