Public class mythread extends thread {
Public void run (){
While (! Thread. currentthread (). isinterrupted ()){
System. Out. println ("current thread id =" + thread. currentthread (). GETID ());
Try {
Thread. Sleep (500 );
} Catch (interruptedexception e ){
System. Out. println (thread. currentthread (). GETID () + "inturrupt ");
Break;
}
}
System. Out. println ("out run ");
}
}
Public class threadtest {
Public static void main (string ARGs []) {
Thread mythread1 = new mythread ();
Mythread1.start ();
Thread mythread2 = new thread (New mythread ());
Mythread2.start ();
Try {
Thread. Sleep (2000 );
} Catch (interruptedexception e ){
E. printstacktrace ();
}
Mythread2.interrupt ();
}
}
The running result is
Sometimes an exception occurs (when sleep is executed in the run loop)
Current thread id = 8
Current thread id = 10
Current thread id = 8
Current thread id = 10
Current thread id = 8
Current thread id = 10
10 inturrupt
Out run
Current thread id = 8
Current thread id = 8
Current thread id = 8
Current thread id = 8
Sometimes jump out of the while loop directly
Current thread id = 8
Current thread id = 10
Current thread id = 10
Current thread id = 8
Current thread id = 10
Current thread id = 8
Current thread id = 8
Out run
Current thread id = 8
Current thread id = 8
Current thread id = 8
Current thread id = 8