多線程多線程程序的輸出預計不會
public class RaceData {
public static void main(String[] args) {
class UnsafeSequence implements Runnable{
private int value = 0;
/** Returns a unique value. */
public void run(){
synchronized (this) {
value = value +1;
System.out.printf("Thread %s and Count value is %d \n",Thread.currentThread().getName(),value);
}
}
}
UnsafeSequence s = new UnsafeSequence();
Thread t1 = new Thread(s);
t1.setName("t1");
t1.start();
Thread t2 = new Thread(s);
t2.setName("t2");
t2.start();
Thread t3 = new Thread(s);
t3.setName("t3");
t3.start();
Thread t4 = new Thread(s);
t4.setName("t4");
t4.start();
Thread t5 = new Thread(s);
t5.setName("t5");
t5.start();
}
}
輸出:
Thread t1 and Count value is 1
Thread t5 and Count value is 2
Thread t3 and Count value is 3
Thread t4 and Count value is 4
Thread t2 and Count value is 5
爲什麼沒有得到正確顯示的計數值? 不好意思,我正在修改我的問題是不是計數變量值, 我預計線程不執行,他們是有序的,但我開始一個其他後t1之後線程T2得到執行,因爲我t1靠後開始T2, 這裏。
那麼,你在期待什麼?什麼是正確的? – 2012-01-04 00:03:50
您對計數值有什麼期望? – 2012-01-04 00:05:12
我想我們已經失去了她。 – 2012-01-04 08:20:17