// Interrupt.java /* Shows how to interrupt a thread (both running and blocked) Execute the program multiple times, and note that most of the time the blocked thread is interrupted, but occasionally the running thread is interrupted instead. by Kip Irvine Updated 1/11/04 */ import java.lang.Thread; class MessageThread implements Runnable { public MessageThread( String msg ) { message = msg; } public void run( ) { try { for( int i = 0; i < 2000; i++ ) { System.out.println( message + i ); // comment out this IF statement to force the thread // to be interrupted only while blocked. if( Thread.currentThread( ).isInterrupted() ) { System.out.println( message + "running thread interrupted" ); return; } Thread.currentThread( ).sleep( 5 ); } } catch( InterruptedException e ) { System.out.println( message + "blocked thread interrupted " ); } } private String message; } class ThreadDemo { public static void main( String[] args ) { Thread t1 = new Thread ( new MessageThread ( "Thread1: " ) ); t1.start( ); try { Thread.currentThread( ).sleep( 1000 ); t1.interrupt( ); } catch( InterruptedException e ) { } } }