【发布时间】:2010-07-23 13:30:28
【问题描述】:
此代码应该产生均匀和不均匀的输出,因为在任何方法上都没有同步。然而,我的 JVM 上的输出总是均匀的。我真的很困惑,因为这个例子直接来自 Doug Lea。
public class TestMethod implements Runnable {
private int index = 0;
public void testThisMethod() {
index++;
index++;
System.out.println(Thread.currentThread().toString() + " "
+ index );
}
public void run() {
while(true) {
this.testThisMethod();
}
}
public static void main(String args[]) {
int i = 0;
TestMethod method = new TestMethod();
while(i < 20) {
new Thread(method).start();
i++;
}
}
}
输出
线程[Thread-8,5,main] 135134
线程[Thread-8,5,main] 135136
线程[Thread-8,5,main] 135138
线程[Thread-8,5,main] 135140
线程[Thread-8,5,main] 135142
线程[Thread-8,5,main] 135144
【问题讨论】:
标签: java multithreading asynchronous