When learn the keyword volatile
, I found https://stackoverflow.com/a/130320/4213589.
I do some changes, but get confusing result. Here is my code:
import java.util.concurrent.*;
public class VolatileTest {
// public static volatile int finished = 0; // 1
public static int finished = 0; // 2
public static void main(String[] args) throws ExecutionException {
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<?> future = executor.submit(()->{
while (finished == 0) {
// when comment the below if-block, result confused
if(Thread.currentThread().isInterrupted()){
System.out.println("???");
break;
}
}
});
executor.submit(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
;
} finally {
finished = 1;
}
});
System.out.println("Started..");
try{
future.get(5, TimeUnit.SECONDS);
System.out.println("finished");
} catch (TimeoutException | InterruptedException e){
System.out.println("timeout!");
} finally {
future.cancel(true);
}
executor.shutdown();
}
}
this code run normally, and output
Started..
finished
but when I comment the if-block in the first submit, output is
Started..
timeout!
But the process is still running, and seems loop no return.
So my question is: the non-empty loop will effect thread reading static variables?