多线程多线程程序的输出预计不会
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