Concurrent Programming Master Series: Thread definition and interrupt interrupt

Source: Internet
Author: User
Tags thread class

1. Three ways to start a thread:

1.1 Inheriting the Thread class

     Public Static class extends Thread {         publicvoid  run () {            System.out.println ("Thread run execution! ");        }    }

To start a thread:

New Usethread (); Ut.start ();

1.2 Implementing the Runable interface

     Public Static class Implements Runnable {        @Override        publicvoid  run () {            System.out.println (" Runable Run Execution! ");        }    }

Start thread

New Userun (); New Thread (UR). Start ();

1.3 Implementing the Callable Interface

     Public Static class Implements Callable<string> {        @Override        publicthrows  Exception {             return "Callable Call Execution! ";        }    }

Start thread

It has a return value and needs to be packaged in Futuretask, such as:

New Usecall (); FuturetaskNew futuretask<>(UC); New Tread (ft). Start (); System.out.println (Ft.get ());

The return value needs to be obtained using the Get method of the future. Execution Result:

Callable Call Execution!

2. Use interrupt to break the thread

Look at a piece of code first

 Public classInterruptTest01 { Public Static classM1ImplementsRunnable { Public voidrun () {Try{System.out.println ("In Run ()-Sleep 20 seconds"); Thread.Sleep (20000); System.out.println ("In Run ()-Wake on Thread"); } Catch(Exception e) {System.out.println ("In Run ()-thread is interrupted in sleep"); //If there is no return, the thread will not actually be interrupted, it will continue to print the following informationSYSTEM.OUT.PRINTLN ("T thread in sleep interrupted after interrupt flag bit status:" +thread.interrupted ()); return; } System.out.println ("In Run ()-the thread has died out properly"); }    }     Public Static voidMain (string[] args) {M1 Si=NewM1 (); Thread T=NewThread (SI); //turn on the T threadT.start (); System.out.println ("The interrupt state of the T thread before calling the Interrupt method:" +t.isinterrupted ()); Try {            //just mark it.T.interrupt (); System.out.println ("The interrupt state of the T thread after calling the interrupt method:" +t.isinterrupted ()); //The main thread sleeps for 2 seconds, ensuring that threads just started have a chance to execute for a whileThread.Sleep (2000); } Catch(interruptedexception e) {System.err.println ("There's something wrong with the main thread catch block."); } System.out.println ("In Main ()-the main thread terminated"); }}

Results of the operation:

The interrupt state of the T thread before calling the interrupt method:false after calling the interrupt method, the T thread's break state:true--  Thread sleep is interrupted when the T thread is interrupted after the interrupt flag bit state:false-The main thread is terminated

Analysis:

Analysis: Thread.Sleep (2000) This method needs to be placed after the interrupt method, if it is placed before, there will be a case where the interrupt flag bit is all false. If you simply call the interrupt () method, the thread is not actually interrupted and will continue to execute.

such as this:

 Public classInterruptTest01 { Public Static classM1ImplementsRunnable { Public voidrun () { while(true) {System.out.println ("I'm not going to break it."); }        }    }     Public Static voidMain (string[] args) {Try{M1 Si=NewM1 (); Thread T=NewThread (SI); //turn on the T threadT.start (); System.out.println ("The interrupt state of the T thread before calling the Interrupt method:" +t.isinterrupted ()); //just mark it.T.interrupt (); System.out.println ("The interrupt state of the T thread after calling the interrupt method:" +t.isinterrupted ()); //The main thread sleeps for 2 seconds, ensuring that threads just started have a chance to execute for a whileThread.Sleep (2000); } Catch(interruptedexception e) {System.err.println ("There's something wrong with the main thread catch block."); } System.out.println ("In Main ()-the main thread terminated"); }}

The result of its operation is spin, which should be judged by the interrupt flag bit in the Run method, as follows:

 Public Static class Implements Runnable {        publicvoid  run () {            while (true) {                 if (thread.interrupted ()) {                    System.out.println ("I should have interrupted");                     return ;                }                System.out.println ("I'm not going to break");     }}}

Result of running again:

The interrupt state of the T thread before calling the interrupt method:false after calling the interrupt method, the T thread's break state:true-The main thread has terminated

3. Pending interruption

This means that if a thread is interrupted before calling the sleep () method, the interrupt is called a pending interrupt, and it immediately throws a Interruptedexception exception when the Sleep () method is called.

As follows:

 Public classPendinginterrupttest { Public Static voidMain (string[] args) {Thread.CurrentThread (). interrupt (); //Get current Time        LongStartTime =System.currenttimemillis (); Try{Thread.Sleep (2000); System.out.println ("The main thread has not been interrupted"); } Catch(Interruptedexception x) {System.out.println ("The main thread was interrupted and entered the catch block."); }        //calculate the time of intermediate code executionSystem.out.println ("Time difference =" + (System.currenttimemillis ()-startTime)); }}

The result of running the code:

=1

What is the difference between 4.interrupted and isinterrupted?

First look at a piece of code

 Public classInterruptTest01 { Public Static classM1ImplementsRunnable { Public voidrun () {System.out.println ("I'm not going to break it."); }    }     Public Static voidMain (string[] args) {Try{M1 Si=NewM1 (); Thread T=NewThread (SI); //turn on the T threadT.start (); System.out.println ("The interrupt state of the 0,T thread before calling the Interrupt method:" +t.interrupted ());            T.interrupt (); System.out.println ("The interrupt state of the 1,t thread after calling the interrupt method:" +t.interrupted ()); System.out.println ("The interrupt state of the 2,t thread after calling the interrupt method:" +t.interrupted ()); //The main thread sleeps for 2 seconds, ensuring that threads just started have a chance to execute for a whileThread.Sleep (2000); } Catch(interruptedexception e) {System.err.println ("There's something wrong with the main thread catch block."); } System.out.println ("In Main ()-the main thread terminated"); }}

The result of the operation is:

The interrupt state of the 0,T thread before calling the interrupt method:false after calling the interrupt method 1,t the interrupt state of the thread:false after calling the interrupt method after 2, The interrupt status of the T thread:false-the main thread terminated

Analysis:

The result is false, and the thread threads do not stop, and the result of calling thread.interrupted () is two false to indicate that the thread has been running for a while. Official explanation: The current thread refers to the thread that runs the this.interrupted () method. That is, the current thread is not T, not because T calls the interrupted () method is the current thread. The current thread has always been the main thread, and it has never been interrupted, so the print result is two false.

Change the code:

 Public classInterruptTest01 { Public Static classM1ImplementsRunnable { Public voidrun () {System.out.println ("I'm not going to break it."); }    }     Public Static voidMain (string[] args) {Try{M1 Si=NewM1 (); Thread T=NewThread (SI); //turn on the T threadT.start (); System.out.println ("The interrupt state of the 0,T thread before calling the Interrupt method:" +thread.interrupted ());            Thread.CurrentThread (). interrupt (); System.out.println ("The interrupt state of the 1,t thread after calling the interrupt method:" +thread.interrupted ()); System.out.println ("The interrupt state of the 2,t thread after calling the interrupt method:" +thread.interrupted ()); //The main thread sleeps for 2 seconds, ensuring that threads just started have a chance to execute for a whileThread.Sleep (2000); } Catch(interruptedexception e) {System.err.println ("There's something wrong with the main thread catch block."); } System.out.println ("In Main ()-the main thread terminated"); }}

Results:

The interrupt state of the 0,T thread before calling the interrupt method:false after calling the interrupt method 1,t the interrupt state of the thread:true after calling the interrupt method after 2, The interrupt status of the T thread:false-the main thread terminated

Analysis:

false false.

Isinterrupt () Method code

 Public Static voidMain (string[] args) {Try{Thread T=Thread.CurrentThread (); System.out.println ("The interrupt state of the 0,T thread before calling the Interrupt method:" +t.isinterrupted ());            T.interrupt (); System.out.println ("The interrupt state of the 1,t thread after calling the interrupt method:" +t.isinterrupted ()); System.out.println ("The interrupt state of the 2,t thread after calling the interrupt method:" +t.isinterrupted ()); //The main thread sleeps for 2 seconds, ensuring that threads just started have a chance to execute for a whileThread.Sleep (2000); System.out.println ("Still in the output?" "); } Catch(interruptedexception e) {System.err.println ("There's something wrong with the main thread catch block."); } System.out.println ("In Main ()-the main thread terminated"); }

Results:

The interrupt state of the 0,T thread before calling the interrupt method:false main thread Catch block problem The interrupt state of the 1,t thread after calling the interrupt method:true  The interrupt state of the 2,t thread after calling the interrupt method:true-the main thread terminated

Analysis:

Once the thread is interrupted, the isinterrupted () method returns True, and once the sleep () method throws an exception, it empties the interrupt flag, and the Isinterrupted () method returns false

Summary above:

Summary: Interrupted (): Tests if the front thread is already in the interrupt state and has the purge status function after execution. Isinterrupted (): Tests whether the thread object is already in a broken state, but does not clear the status flag.

Concurrent Programming Master Series: Thread definition and interrupt interrupt

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.