我正在学习Java中的同步,我不知道为什么我不能得到24000作为"c.count"的结果。当我运行代码时,我得到23674、23853等。你知道为什么吗?
public class Counter {
public int count = 0;
public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();
ThreadT t1 = new ThreadT(c);
ThreadT t2 = new ThreadT(c);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(c.count);
}
}
class ThreadT extends Thread {
Counter c;
ThreadT(Counter c) {
this.c = c;
}
public void run() {
for (int i = 0; i < 12000; i++) {
add();
}
}
synchronized void add() {
c.count++;
}
}```
注意,t1
在t1
对象上调用add
,而t2
在t2
对象上调用add
。虽然add
是同步的,但t1
和t2
是两个不同的对象,因此两个线程不会相互同步。
每个线程在自己的线程对象上调用synchronized方法,因此它只与自己同步。你需要两个线程在同一个对象上调用同步方法。