我正在刷我的多线程基础知识。要了解我在以下程序中创建的同步 -
package thread;
public class SynchronizedCounter implements Runnable{
private static int counter = 0;
public void run() {
while(counter < 10) {
synchronized (SynchronizedCounter.class) {
System.out.println(Thread.currentThread().getName() + " :: reads ## " + counter);
counter++;
System.out.println(Thread.currentThread().getName() + " :: updated value ## " + counter);
}
}
}
public static void main(String[] args) {
Thread[] threads = new Thread[5];
for(int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new SynchronizedCounter(), "Thread-" + i);
threads[i].start();
}
for(int i = 0; i < threads.length; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
现在当我执行时,得到了这个结果:
Thread-0 :: reads --> 0
Thread-0 :: updated value --> 1
Thread-3 :: reads --> 1
Thread-3 :: updated value --> 2
Thread-0 :: reads --> 2
Thread-0 :: updated value --> 3
Thread-0 :: reads --> 3
Thread-0 :: updated value --> 4
Thread-0 :: reads --> 4
Thread-0 :: updated value --> 5
Thread-0 :: reads --> 5
Thread-0 :: updated value --> 6
Thread-0 :: reads --> 6
Thread-0 :: updated value --> 7
Thread-0 :: reads --> 7
Thread-0 :: updated value --> 8
Thread-0 :: reads --> 8
Thread-0 :: updated value --> 9
Thread-0 :: reads --> 9
Thread-0 :: updated value --> 10
Thread-1 :: reads --> 10
Thread-1 :: updated value --> 11
Thread-2 :: reads --> 11
Thread-2 :: updated value --> 12
Thread-4 :: reads --> 12
Thread-4 :: updated value --> 13
Thread-3 :: reads --> 13
Thread-3 :: updated value --> 14
一切看起来都不错,但是我无法理解为什么“计数器”的值超过10。虽然循环传递虽然值是13或14超过10.我理解当控制试图进入时它可能读取不同的值,当它到达第一次打印时,即“:: reads - &gt;”。但理想情况下,任何线程都应该将此值增加到10.请帮助我了解我缺少的位置。
谢谢!!
答案 0 :(得分:3)
因为synchronized(SynchronizedCounter.class)在while循环中。想象计数器命中9.所有线程仍然可以进入while块,然后一个将运行,将计数器递增到10.它将退出synchronized块,允许另一个线程运行,将计数器递增到11.这样每个都继续线程,所以计数器将命中14.然后下一次通过while循环,计数器&lt; 10测试将失败,他们将全部从run()返回,从而退出。
我猜另一个计数器&lt;同步块内的10个测试将修复它。