Java concurrent programming principle and actual combat four: how threads are interrupted

Source: Internet
Author: User

If you have used anti-virus software, you may find that the overall antivirus too time-consuming, then if you click the Cancel Antivirus button, then you are interrupting a running thread.

Java gives us a way to call the interrupt () method to request a terminating thread, so let's take a look at the thread break.

Each thread has a Boolean type flag that indicates whether the current thread is requesting an interrupt, and when a thread calls the interrupt () method, the thread's interrupt flag is set to true.

We can detect if the thread's interrupt flag is set by calling Thread.CurrentThread (). isinterrupted () or thread.interrupted (). The difference between the two methods is that

Thread.CurrentThread (). isinterrupted () is a method of a thread object that does not clear the thread interrupt flag bit after it is called, and thread.interrupted () is a static method that is called to clear the

Thread interrupt flag bit.

Thread.CurrentThread (). isinterrupted (): Object method does not clear interrupt flag bit

Thread.interrupted (): Static method clears the interrupt flag bit (set to false)

So the interrupt () method of the calling thread does not break a running thread, this mechanism just sets a thread interrupt flag bit, if you do not detect thread interrupt flag bit in the program, then even if

Set the interrupt flag bit to true and the thread will run as usual.

In general, the thread break is divided into three cases:

(i): Interrupts non-blocking threads

(ii): Interrupt blocking thread

(c): Not to break the thread

(i): Interrupts non-blocking threads

There are usually two ways to break a non-blocking thread:

(1) Using Thread sharing variables

This is a simple and feasible way to note that a shared variable must be set to volatile to ensure that other threads are immediately visible after the modification.

 Public classInterruptthreadtestextendsthread{//set thread share variables    volatile BooleanIsstop =false;  Public voidrun () { while(!isstop) {            LongBeginTime =System.currenttimemillis (); System.out.println (Thread.CurrentThread (). GetName ()+ "is running"); //The current thread detects if a thread-sharing variable is notified every second             while(System.currenttimemillis ()-BeginTime < 1000) {}        }        if(isstop) {System.out.println (Thread.CurrentThread (). GetName ()+ "is interrupted"); }    }         Public Static voidMain (string[] args) {//TODO auto-generated Method StubInterruptthreadtest ITT =Newinterruptthreadtest ();        Itt.start (); Try{Thread.Sleep (5000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        //thread share variable set to TrueItt.isstop =true; } }

(2) Use of interrupt mechanism

The code is as follows:

 Public classInterruptThreadTest2extendsthread{ Public voidrun () {//the Isinterrupted method that is called here is a non-purge interrupt flag bit         while(!Thread.CurrentThread (). isinterrupted ()) {            LongBeginTime =System.currenttimemillis (); System.out.println (Thread.CurrentThread (). GetName ()+ "is running"); //The current thread detects if the thread interrupt flag bit is set at every second             while(System.currenttimemillis ()-BeginTime < 1000) {}        }        if(Thread.CurrentThread (). isinterrupted ()) {System.out.println (Thread.CurrentThread (). GetName ()+ "is interrupted"); }    }         Public Static voidMain (string[] args) {//TODO auto-generated Method StubInterruptThreadTest2 ITT =NewInterruptThreadTest2 ();        Itt.start (); Try{Thread.Sleep (5000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        //set the interrupt flag bit for a threadItt.interrupt (); }}

(ii): Interrupt blocking thread

When a thread calls Thread.Sleep (), Thread.Join (), object.wait (), or calls a blocking I/O operation method, it causes the current thread to enter a blocking state. At this point, if the thread is in a blocked state, it is called

What happens when the interrupt () method sets the thread interrupt flag bit? A thread that is in a blocking state throws an exception and clears the thread interrupt flag bit (set to false). So that the thread can exit

Blocking state. Of course, the way to throw exceptions is Thread.Sleep (), Thread.Join (), object.wait (), which cause threads to be in a blocking state.

The code example is as follows:

 Public classInterruptThreadTest3extendsthread{ Public voidrun () {//the Isinterrupted method that is called here is a non-purge interrupt flag bit         while(!Thread.CurrentThread (). isinterrupted ()) {System.out.println (Thread.CurrentThread (). GetName ()+ "is running"); Try{System.out.println (Thread.CurrentThread (). GetName ()+ "Thread.Sleep Begin"); Thread.Sleep (1000); System.out.println (Thread.CurrentThread (). GetName ()+ "Thread.Sleep End"); } Catch(interruptedexception e) {//TODO auto-generated Catch block//because calling the sleep () method clears the status flag bit, it needs to reset the interrupt flag bit again otherwise the thread will continue to runThread.CurrentThread (). interrupt ();            E.printstacktrace (); }        }        if(Thread.CurrentThread (). isinterrupted ()) {System.out.println (Thread.CurrentThread (). GetName ()+ "is interrupted"); }    }         Public Static voidMain (string[] args) {//TODO auto-generated Method StubInterruptThreadTest3 ITT =NewInterruptThreadTest3 ();        Itt.start (); Try{Thread.Sleep (5000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        //set the interrupt flag bit for a threadItt.interrupt (); }}

It is important to note that the Thread.Sleep (), Thread.Join (), object.wait () methods detect the thread interrupt flag bit and throw an exception if the interrupt flag bit is found to be true and set the interrupt flag bit to false.

So after each call to the blocking method after the while loop, after the exception is caught, call Thread.CurrentThread (). Interrupt () Resets the status flag bit.

(c): Not to break the thread

There is a case where threads cannot be interrupted, that is, the process of calling the Synchronized keyword and reentrantlock.lock () to get the lock.

However, if the Trylock method with timeout is called Reentrantlock.trylock (longtimeout, Timeunit unit), a Interruptedexception exception is thrown if the thread is interrupted while waiting. This is a very

Useful feature because it allows programs to break deadlocks. You can also call the reentrantlock.lockinterruptibly () method, which is equivalent to a timeout set to an infinite Trylock method.

 Public classINTERRUPTTHREADTEST5 { Public voidDeathlock (Object Lock1, Object Lock2) {Try {            synchronized(lock1) {System.out.println (Thread.CurrentThread (). GetName ()+ "is running"); //let another thread get another lockThread.Sleep (10); //cause a deadlock                synchronized(Lock2) {System.out.println (Thread.CurrentThread (). GetName ()); }            }        } Catch(interruptedexception e) {System.out.println (Thread.CurrentThread (). GetName ()+ "is interrupted");        E.printstacktrace (); }    }         Public Static voidmain (String [] args) {FinalINTERRUPTTHREADTEST5 ITT =NewInterruptThreadTest5 (); FinalObject Lock1 =NewObject (); FinalObject Lock2 =NewObject (); Thread T1=NewThread (NewRunnable () { Public voidrun () {Itt.deathlock (lock1, Lock2); }        },A); Thread T2=NewThread (NewRunnable () { Public voidrun () {Itt.deathlock (Lock2, LOCK1); }        },B);        T1.start ();        T2.start (); Try{Thread.Sleep (3000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        //Middle thread break T1, T2T1.interrupt ();    T2.interrupt (); }}

Other study articles refer to:

How do I stop a thread correctly?

Java thread break mechanism-how to break thread in

Java concurrent programming principle and actual combat four: how threads are interrupted

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.