简体   繁体   English

Java同步方法无法按预期工作

[英]Java synchronized method does not work as expected

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. 我的输出总是像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. 我该如何解决这个问题,我知道我可以检查count的值,如果它不是我期望的值,我可以一遍又一遍地调用运行,但这对我没有任何帮助。 synchronized keyword shouldn't fix that situation ? 同步关键字不应该解决这种情况吗?

What am I missing ? 我想念什么?

Solution : Printing count after join fixed my problem. 解决方案:加入后打印计数解决了我的问题。

If you join the threads before priniting the result and make count volatile, you will always get 200. 如果在确定结果的优先级之前加入线程并使计数易变,则总会得到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. 从t1和t2进行计数的访问工作正常,因为增量方法在同一个对象上同步,并且在线程上调用join创建一个事前发生的关系。 Thus, the main thread is guaranteed to see a correct value of count even without volatile, too. 因此,即使没有volatile,也可以确保主线程看到正确的count值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM