这段代码应该产生均匀和不均匀的输出,因为在任何方法上都没有同步。然而,我的 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
最佳答案
我尝试使用 volatile
并得到以下结果(使用 if
仅在奇数时打印):
Thread[Thread-12,5,main] 122229779
Thread[Thread-12,5,main] 122229781
Thread[Thread-12,5,main] 122229783
Thread[Thread-12,5,main] 122229785
Thread[Thread-12,5,main] 122229787
回复评论:
索引实际上是共享的,因为我们有一个 TestMethod
实例,但许多 Thread
调用 testThisMethod()
一个 我们拥有的测试方法
。
代码(除了上面提到的以外没有变化):
public class TestMethod implements Runnable {
volatile private int index = 0;
public void testThisMethod() {
index++;
index++;
if(index % 2 != 0){
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++;
}
}
}
关于Java 6 线程输出不是异步的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3318554/