This code is from Effective Java (paragraph 66): (without synchronization or instability, it never ends)
public class ThreadPractice { static boolean canrunstatic; public static void main(String[] args) throws InterruptedException { Thread backgroundThread = new Thread(new Runnable() { public void run() { int i = 0; while (!canrunstatic){i++;} System.out.println("finished"); } }); backgroundThread.start(); TimeUnit.SECONDS.sleep(1); canrunstatic = true; }
As Bloch mentioned in this chapter, he will never write "finished" to the console. I played with this class and add this line to the runnable run method:
System.out.println("im still running");
In this case, the while loop not only increases i, but also displays this line in each cycle. But what drives me crazy, so the thread stops after 1 second when the main thread returns from sleep.
changed: (stops without mutability / synchronization)
public class ThreadPractice { static boolean canrunstatic; public static void main(String[] args) throws InterruptedException { Thread backgroundThread = new Thread(new Runnable() { public void run() { int i = 0; while (!canrunstatic){i++;System.out.println("im still running");} System.out.println("finished"); } }); backgroundThread.start(); TimeUnit.SECONDS.sleep(1); canrunstatic = true; }
So what is the logic behind this?
source share