I am trying to construct two threads, thread A is the main thread and thread B is the second thread, thread B is updating a variable through a time consuming function (this variable should be shared between both threads, because eventually thread A needs to use that variable as well), but I want thread A to terminate thread B if thread B takes too long to complete (using an exception).
What I tried is the following:
Thread thread = new Thread() {
public void run() {
/// run something that could take a long time
}
};
synchronized (thread) {
thread.start();
}
System.err.println("Waiting for thread and terminating it if it did not stop.");
try {
thread.wait(10000);
} catch (InterruptedException e) {
System.err.println("interrupted.");
}
Should that give the expected behavior of terminating a behavior in case it has run more than 10 seconds? The thread object gets deleted after the wait, because the method that runs the thread returns.
Right now, what happens with this code is that I always get java.lang.IllegalMonitorStateException on the wait(10000) command.
You will always get a
IllegalMonitorStateExceptionif you are callingwait()on an object that you are notsynchronizedon.If you are waiting for the
threadto finish then you probably are trying to do a:Unfortunately, you do not know at that point if the thread is running because
joindoesn’t return whether or not it timed out (grumble). So you need to test if thethread.isAlive()after the join.If you are asking how you can cancel the
threadif it runs for longer than10000millis, then the right thing to do is usethread.interrupt(). This will cause anysleep()orwait()methods to throw anInterruptedExceptionand it will set the interrupt flag on the thread.To use the interrupt flag your thread should be doing something like:
Also, it is always a good pattern to do something like the following because once the
InterruptedExceptionis thrown, the interrupt flag has been cleared: