我为什么要
22291 3091 0 351 0 1423 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 + " ");
}
}发布于 2014-11-01 22:09:38
得到这个输出是因为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
}https://stackoverflow.com/questions/26693707
复制相似问题