为什么我
22291 3091 0 351 0 1423 0 0 0 0
而不是
0 0 0 0 0 0 0 0 0 0
当我在Java中运行此代码时:
import java.lang.Thread;
class MainThread {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) new MyThread().start();
}
}
class MyThread extends Thread {
static int counter = 0;
static Object mutex = new Object();
public void run() {
synchronized (mutex) {
for (int i = 0; i < 1000000; i++) counter = counter + 1;
for (int i = 0; i < 1000000; i++) counter = counter - 1;
}
System.out.print(counter + " ");
}
}
答案 0 :(得分:2)
您获得该输出,因为print语句未同步。在thread
完成两个for循环后,syncronized
块中存在counter = 0
。
但在打印出counter
之前,其他一些线程进入syncronized
块并开始递增counter
。
这就是为什么之前的thread
打印增加的counter
。
public void run() {
synchronized (mutex) {
for (int i = 0; i < 1000000; i++) counter = counter + 1;
for (int i = 0; i < 1000000; i++) counter = counter - 1;
}
// Here the current thread exited the sync block and some other thread get into this block
// and started incrementing the counter
System.out.print(counter + " "); // your thread prints incremented counter
}