I am writing a code using Java volatile keyword now and I am wondering why thread stops after I press enter for 2-3 times, not just 1 time. The code:
public class RunThread {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
myThread.shutDown();
}
}
class MyThread extends Thread {
public volatile boolean running = true;
public void run() {
while (running) {
System.out.println("Hello");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void shutDown() {
this.running = false;
}
}
Thanks in advance for you help!