Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How does thread.interrupt() work

skidmarksMar 20 2011 — edited Mar 20 2011
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)
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 17 2011
Added on Mar 20 2011
6 comments
535 views