Does this variable need to be declared volatile?
Posted
by titaniumdecoy
on Stack Overflow
See other posts from Stack Overflow
or by titaniumdecoy
Published on 2010-05-29T05:28:48Z
Indexed on
2010/05/29
5:32 UTC
Read the original article
Hit count: 258
Does the out
variable in the MyThread class need to be declared volatile in this code or will the "volatility" of the stdout
variable in the ThreadTest class carry over?
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();
}
}
}
© Stack Overflow or respective owner