[英]Synchronizing 10 threads in Java
我為什么得到
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 + " ");
}
}
您得到該輸出,因為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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.