I was writing a program of thread that contains a loop that sleeps for 30 seconds and the loop executes until a “shutdown” flag is set to true on the runnable object executing in the thread.
class MyThread extends Thread{
//set this to true to stop the thread
volatile boolean shutdown = false;
public void stopMe() {
shutdown=true;
}
public void run () {
while (!shutdown) {
// continue processing
try {
Thread.sleep(30000);
} catch (InterruptedException e) {}
}
}
}
But when the shutdown flag is set to true, will the thread exit immediately? What if it is in the sleep call? How can the thread be woken up immediately by another thread? Please help to get answers to these questions as am learning threading