004 Thread interrupt method

I. Overview

The interrupt method of a thread is a method used to interrupt a thread, which we can understand as sending a signal to a thread.

  By monitoring this signal, the thread can terminate its own life cycle by itself.


 

2. Examples

public static void main(String[] args) {
        
        final Thread t1 = new Thread() {
            @Override
            public void run() {
                while(!isInterrupted())
                    System.out.println("runing......");
                
                System.out.println("interrupt .....");
            }
        };
        t1.start();
        
        // Create thread 2 
        new Thread() {
            @Override
            public  void run() {
                 try {
                     // First sleep for 3 seconds 
                    Thread.sleep( 3000 );
                } catch (InterruptedException e) {
                    e.printStackTrace ();
                }
                // After the sleep is completed, interrupt the t1 thread
                 // will send an interrupt message 
                t1.interrupt();
            }
        }.start();
    }    

3. Summary

When we use interrupt, we need to write our own code to monitor thread status.

  When a thread is interrupted, the thread gets an interrupted exception.

  at this time:

       [1] The interrupt status word of the thread has been modified

      [2] will also get an exception

  therefore:

    [1] We can control the termination of a thread by checking the status word

    [2] The termination of the thread is done by catching the exception.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325137339&siteId=291194637