luc*_*uta 2 java multithreading
为什么这个程序在每次执行时都不会显示2000?我知道我可以使用AtomicInteger,但我很好奇.
class Increment extends Thread{
static Integer i=new Integer(0);
public void run(){
for(int j=1;j<=1000;j++){
synchronized (i) {
i++;
}
}
}
}
public class Puzzle {
public static void main(String args[]) {
Thread t1=new Increment();
Thread t2=new Increment();
t1.start();
t2.start();
try {
t1.join();
t2.join();
}catch (InterruptedException r){}
System.out.println(Increment.i);
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*nik 10
您在可变变量上同步i.此变量每次都会更改其值,因此每次获取另一个对象的锁定时.因此,每个线程获得非竞争锁并且可以同时进行,就像没有同步一样.
课程:使用专用private static final Object lock = new Object()作为锁.
| 归档时间: |
|
| 查看次数: |
779 次 |
| 最近记录: |