Viv*_*aya 1 java multithreading synchronization
我做了一些研究,但我猜不出正确答案.
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的输出总是不同,如200,182,171,65,140.我怎么能解决这个问题我知道我可以检查计数的值,如果它不是我预期的值,我可以一次又一次地调用运行但它对我没有任何帮助.synchronized关键字不应该解决这种情况?
我错过了什么?
解决方案:加入后打印计数修复了我的问题.
如果在打印结果之前加入线程并使计数变为volatile,则总是会得到200.
虽然挥发性在这里没有伤害,但没有必要.从t1和t2计数的访问正常工作,因为increment方法在同一个对象上同步,并且在线程上调用join创建了一个before-before关系.因此,即使没有volatile,主线程也能保证看到正确的count值.
| 归档时间: |
|
| 查看次数: |
226 次 |
| 最近记录: |