以下代码给出的固定输出为400000000,而当我从同步的addOne方法中删除static关键字时,我得到的随机输出是小于400000000的任何整数。
谁能解释一下?

public class ThreadTest extends Thread{

public static int sharedVar = 0;

private static synchronized void addOne()
{
    for (int i = 0; i < 200000000; i++)
    {
        sharedVar++;
    }
}

@Override
public void run()
{
    addOne();
}

public static void main(String[] args)
{
    ThreadTest mt1 = new ThreadTest();
    ThreadTest mt2 = new ThreadTest();
    try
    {
        // wait for the threads
        mt1.start();
        mt2.start();
        mt1.join();
        mt2.join();
        System.out.println(sharedVar);
    }
    catch (InterruptedException e1)
    {
        e1.printStackTrace();
    }
}
}

最佳答案

稍微更改您的addOne()方法,如下所示以了解其行为。

private static synchronized void addOne() {
    for (int i = 0; i < 5; i++) {
        sharedVar++;
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
        }
        System.out.println(Thread.currentThread().getName());
    }
}


使用static的输出是:

Thread-0
Thread-0
Thread-0
Thread-0
Thread-0
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1


没有static的输出是:

Thread-0
Thread-1
Thread-0
Thread-1
Thread-0
Thread-1
Thread-1
Thread-0
Thread-0
Thread-1


如果您需要更多信息以了解它,请参考oracle thread synchronization tutorial

关于java - 静态同步方法Java,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37819462/

10-11 22:28
查看更多