What I would like to do is cause an interrupt of the main thread in the Timer thread and catch the interrupt in the main thread, but the 'catch(InterruptedException)' in the main thread has an unreachable error. I am confused. The 'interrupted()' is not static and so I assume that 'thread.interrupt()' will cause and interrupt in 'thread', the main thread, but I can't seem to be able to catch it. Any idea what I'm doing wrong and how to fix the problem?
public static Message receive(int milliseconds, BufferedInputStream in) {
Message message; // Message return value
class Timer implements Runnable {
Thread thread; // Calling thread
int milliseconds; // Timeout in milliseconds
public Timer(Thread thread, int milliseconds) {
this.thread = thread;
this.milliseconds = milliseconds;
} // public Timer(Thread thread, int milliseconds)
@Override
public void run() {
try {
Thread.sleep(milliseconds);
thread.interrupt(); // timer expired before input achieved
} catch (InterruptedException e) {
// input received before timer expired
}
} // public void run()
} //Timer implements Runnable
if (milliseconds <= 0)
message = receive(in);
else {
try {
Thread timer = new Thread(new Timer(Thread.currentThread(), milliseconds));
timer.start();
message = receive(in);
timer.interrupt();
} catch (InterruptedException{
// Do something, in desperation if you have to.
}
}
return message;
} // Message receive(int time, BufferedInputStream in)
}