Ok, I was asked this multi-threading question in an interview. The question was something like this
public class Job {
static boolean interruptTask = false;
private static class Mytask extends Thread{
@Override
public void run() {
while(!interruptTask){
//do some time consuming thing until interruption like looping over millions of times
}
}
}
public static void main(String[] args) throws InterruptedException {
Mytask t = new Mytask();
t.run();
Thread.sleep(1000);
interruptTask=true;
t.join();
System.out.println("end");
}
}
Question statement
What is wrong with this code snippet and how will you fix it.
I was able to identify the problem here. The problem in my opinion is that even when we make the interrupttask variable true in the main function, it does not interrupt the thread. The thread will keep on doing until its long time taking execution is not over.
But I can't figure out the solution for this problem? I mean, we have tools like wait,notify for thread, but I don't those are somethings we can use here. What should be the approach to resolve this particular issue in this scenario?
Can anyone help me figure out the solution of this problem? or some guidance regarding how should I go about for the solution?