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();
}
}
}