【发布时间】:2010-05-29 05:28:48
【问题描述】:
MyThread 类中的out 变量是否需要在此代码中声明为 volatile,或者 ThreadTest 类中的stdout 变量的“波动性”是否会延续?
import java.io.PrintStream;
class MyThread implements Runnable
{
int id;
PrintStream out; // should this be declared volatile?
MyThread(int id, PrintStream out) {
this.id = id;
this.out = out;
}
public void run() {
try {
Thread.currentThread().sleep((int)(1000 * Math.random()));
out.println("Thread " + id);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class ThreadTest
{
static volatile PrintStream stdout = System.out;
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(new MyThread(i, stdout)).start();
}
}
}
【问题讨论】:
标签: java multithreading volatile