java thread interrupts Interrupted usage

The main mechanism to stop a thread is interrupted, the interrupt does not represent forced to terminate a thread,

It is a cooperative mechanism, a signal is passed to the thread cancellation,

But let thread to decide how and when to exit.

This sentence can be described as the core principle of the interrupted thread; just look at the text is still very vague, with a bar code for that matter.

. 1  public  class ThreadEnd the implements the Runnable {
 2  
. 3      Private  volatile  static  Boolean OK = to false ;
 . 4      @Override
 . 5      public  void RUN () {
 . 6         for (;;) {
 . 7              IF (. Thread.currentThread () isInterrupted ()) {
 . 8                  the System .out.println ( "I entered the condition of interrupt threads, it will be the end of the run method" );
 9                  bREAK ; // because it is for an infinite loop, the loop exits this way 
10              } the else {
 11                 System.out.println ( "I did not receive interrupt information" );
 12 is              }
 13 is          }
 14      }
 15  
16  
. 17  
18 is      public  static  void main (String [] args) throws InterruptedException {
 . 19          the Thread Thread = new new the Thread ( new new ThreadEnd () );
 20 is          Thread.start ();
 21 is          the Thread.sleep (1000 );
 22 is          Thread.interrupt ();
 23 is          System.out.println ( "end main thread" );
 24  
25      }
 26 }

In line 6 to stop the cycle of death viewing thread isInterrupted () method returns true;

The first 22 lines of code to the thread calls interrupt thread method, line 7 conditions are met, the final out of the thread.

So there is a question: is not all threads may be interrupted by both interrupt () methods?

For example, sleep thread, such as thread waiting for the lock? Our one by one to solve it.

sleep sleeping thread interrupt code

. 1  public  class InterruptionSleepThread the implements the Runnable {
 2  
. 3      @Override
 . 4      public  void RUN () {
 . 5          the try {
 . 6              System.out.println ( "Sleep uncle to 50 seconds, you can Naiwo?" );
 . 7              the Thread.sleep ( 50000); // sleep 50 seconds 
. 8          } the catch (InterruptedException E) {
 . 9              System.out.println ( "dormant thread interrupt is received by Throws manner uncle wake from a dream, the end of the thread." );
 10              e.printStackTrace ();
 . 11          }
 12 is      }
13     public static void main(String[] args) throws InterruptedException {
14         Thread thread = new Thread(new InterruptionSleepThread());
15         thread.start();
16         Thread.sleep(2000);
17         thread.interrupt();
18         System.out.println("主线程结束");
19 
20     }
21 }

Print results

 

 

From the above results, print run, dormant threads is indeed withdraw, although this is not very elegant way to wake up (in unusual ways).

It also tells us from another point of view, why every time at run time calling sleep () method () inside, we force the compiler to capture the anomaly, but also for the security program.

Process waiting for the lock, the code is interrupted

. 1  public  class WaitLockThreadInterrupted the extends the Thread {
 2  
. 3      Private  static Object Lock = new new Object ();
 . 4  
. 5      @Override
 . 6      public   void RUN () {
 . 7          System.out.println ( "I want to wait for the lock release test, to perform the following Code " );
 8          the synchronized (Lock) {
 9            the while ( to true ) {
 10                IF (Thread.currentThread () isInterrupted ()) {.
 11                    System.out.println (" I have received interrupt signal thread " );
 12                    bREAK;
13               }else{
14                   System.out.println("没收到线程中断的信号");
15               }
16           }
17         }
18     }
19 
20     private static void test() throws InterruptedException {
21         synchronized (lock){
22             Thread thread=new Thread(new WaitLockThreadInterrupted());
23             thread.start();
24             Thread.sleep(1000);
25              Thread.interrupt ();
 26              System.out.println ( "has issued the interrupt signal" );
 27              Thread.join (); // blocking test method, thread until the thread is finished. 
28          }
 29      }
 30  
31 is      public  static  void main (String [] args) throws InterruptedException {
 32        Test ();
 33 is      }
 34 is }

Print results

 

Although the printed result, but the left side of the red light has been lit, and there is no print 11 lines, it indicates that the thread has not withdraw.

Analysis Code: test in a synchronized () method and run synchronized with the same lock object,

Therefore, the implementation of thread run method of the thread 22 rows, you must wait until the test relieved lock lock objects for the job;

But the test with thread.join () method to tell us, thread and other thread is finished, I can let you go.

Over, deadlock.

This deadlock state if 25 lines of code sends an interrupt signal useful, this is embarrassing deadlock can unlock.

From the printing results, interrupt () is not interrupted threads wait for a lock.

in conclusion:

1.Runnable state (running or waiting for scheduled threads) can interrupt () interrupts

2.Block state (wait for the lock thread) can not use the interrupt () interrupts

 

Guess you like

Origin www.cnblogs.com/guoyansi19900907/p/12585601.html