When I run my program, I see the below output -
Type something
Hello
Hello
Hello
-
My question is why does the Type something statement even get printed? proc1.start() calls the run method, and since there is an infinite loop in the run method, it should never come out of the run method. Is Thread.sleep(100) causing this? Can someone please explain? I am clearly missing something simple here. Here is the code -
public class Processor extends Thread {
private boolean running = true;
public void run() {
try {
while (running) {
System.out.println("Hello");
Thread.sleep(100);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void shutdown() {
running = false;
}
public static void main(String[] args) {
Processor proc1 = new Processor();
proc1.start();
System.out.println("Type something");
Scanner scan = new Scanner(System.in);
scan.nextLine();
proc1.shutdown();
}
}
The reason "Type something" gets printed is because by calling proc1.start()
, you are starting another Thread
. This Thread
runs concurrently with the main thread. So, in reality this snippet of code has 2 threads. The main thread is responsible for printing "Type something" and the Processor Thread
is responsible for printing "Hello" every 100 seconds.
When you call proc1.start()
, the line of code does not block on that line. Instead, the program will call that line, start Processor
Thread
and then keep running main.