There is my code
public class Test {
private static boolean running = true;
public static void main(String[] args) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "get running:" + running);
while (running) {
}
System.out.println(Thread.currentThread().getName() + "end");
}, "t1").start();
new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
running = false;
System.out.println(Thread.currentThread().getName() + "change running to:" + running);
}, "t2").start();
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "get running:" + running);
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "get running:" + running);
}, "t3").start();
}
}
console output
t1get running:true
t3get running:true
t2change running to:false
t3get running:false
so the thread t1
is stuck in while loop. And I know if I change running
to private static volatile boolean running
can fix this.
I question is t3
and t2
are different thread to, why t3
can get the new value of running
but t1
can't
EDIT1
@andrew-tobilko said it may because I call Thread.sleep
in the loop body, so I change the code of t3
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "get running:" + running);
long start = System.nanoTime();
long now = System.nanoTime();
while ((now-start)<3*1000L*1000L*1000L){
now = System.nanoTime();
}
System.out.println(Thread.currentThread().getName() + "get running:" + running);
}, "t3").start();
the result still the same
t1
waits also in the loop body: demo. So it probably has something to do thatwhile(running) {}
will be converted to awhile(true) {}
loop by the JIT compiler, because it has been deemed a hotspot – Jayjayceerunning
so partucular JVM implementation you are using can do whatever it wants regarding visibility if that variable in different threads. Some threads may see initial value, some may see new value – Moneyed