Interrupt Java threads

introduction

Java does not provide any mechanism to safely terminate the thread, but provides interrupt mechanism, namely thread.interrupt () method. Interrupt thread is a collaborative mechanisms, not to say that the method is called after an interruption of the target thread will be interrupted immediately, but sends an interrupt request to the target thread, the target thread will cancel itself at some point interrupted himself. This setting is necessary because no matter if the thread execution to all circumstances immediate interrupt, then it is likely to cause some inconsistent object state occurs.

text

First, the interrupt associated method introduced

Thread basis method involves interruption of three: interrupt (), isInterrupted (), interrupted (), which are located under the Thread class. Under Thread class also has a

interrupt () method: send an interrupt request to the target thread, look at its source code will find final thread is to call a native method implemented interrupt;

interrupted () method: returns a Boolean value of the target thread is interrupted (implemented by local method), reset after interruption and return to a status of not interrupt;

isInterrupted () method: This method returns a Boolean value thread is interrupted or not (through local method), does not reset the interrupt status;

Second, the thread is interrupted

Thread interrupts can be interrupted by a thread state is divided into two categories, one is the thread run interrupts, one is blocked waiting for an interrupt or thread. When an interrupt, the thread will run at some point break execution cancel, or wait thread is in a blocked state would most likely immediate interrupt, such as on a join, sleep and other methods mentioned in the article, these methods throw after an interruption error exceptions, interrupt reset the thread state is not interrupted. But note, to obtain an exclusive lock blocking state and BIO blocking state does not respond to interrupts. While during the locking method of blocking the response to interrupt the JUC package, such lockInterruptibly ().

The following three questions to tell the story thread interrupts

1. What is the purpose of the thread break?

Why should the thread break? Sometimes due to certain circumstances, we do not need to know the current thread to continue execution, then you can interrupt this thread; sometimes you encounter some unexpected need to interrupt thread. What specific purpose, but also the specific scene, but demand has been interrupted thread out there, definitely you need.

2, how to deal with thread interrupts?

There are two common approach, if it is the operational level of the code, you only need to do the business logic processing after the interrupt thread, and if it is partial function of the underlying thread is interrupted, try to interrupt an exception is thrown (or at catch the recall interrupt () to interrupt thread) to inform the method of the upper thread interrupt experience.

3, JUC of the interrupt handling Examples

JUC in locking method is commonly used ReentrantLock lock (), there is a locking method lockInterruptibly in response to interrupts ()

lock () method acquire (int arg) shown as follows:

1 public final void acquire(int arg) {
2         if (!tryAcquire(arg) &&
3             acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
4             selfInterrupt();
5 }

In acquireQueued the thread's interrupt status will have to make a judgment, if interrupted returns true, enter selfInterrupt () method to restore thread's interrupt status. But note here that after obtaining the lock and then respond to the interrupt, before acquiring the lock does not respond.

1 static void selfInterrupt() {
2         Thread.currentThread().interrupt();
3 }

And look lockInterruptibly () method:

 1 public void lockInterruptibly() throws InterruptedException {
 2         sync.acquireInterruptibly(1);
 3     }
 4 
 5 public final void acquireInterruptibly(int arg)
 6             throws InterruptedException {
 7         if (Thread.interrupted())
 8             throw new InterruptedException();
 9         if (!tryAcquire(arg))
10             doAcquireInterruptibly(arg);
11     }

It will first see the interrupt status, then get the lock. And if interrupted in the process of acquiring the lock, the interrupt exception will be thrown in doAcquireInterruptibly method.

 Here is my blocking interruption in local analog of lock:

 1 public class ReentrantLockDemo {
 2     public static void main(String[] args) throws InterruptedException {
 3         System.out.println("main start");
 4         Thread thread1 = new Thread(new LockThreadDemo());
 5         Thread thread2 = new Thread(new LockThreadDemo());
 6         thread1.start();
 7         Thread.sleep(1000); // 确保thread1获取到了锁
 8         thread2.start(); // 此时thread2处于获取锁的阻塞状态
 9         thread2.interrupt();
10         System.out.println("main end");
11     }
12 }
13 
14 class LockThreadDemo implements Runnable {
15     public static ReentrantLock lock = new ReentrantLock();
16     @Override
17     public void run() {
18         System.out.println(Thread.currentThread().getName() + "runnable run");
19         try {
20             lock.lock();
21             System.out.println(Thread.currentThread().getName() + "开始睡眠");
22             Thread.sleep(5000);
23             System.out.println(Thread.currentThread().getName() + "睡了5秒");
24         } catch (Exception e) {
25             System.out.println(Thread.currentThread().getName() + "runnable exception:" + e);
26         } finally {
27             lock.unlock();
28         }
29         System.out.println(Thread.currentThread().getName() + " over");
30     }
31 }

Implementation of the results:

main start
Thread-0runnable run
The Thread - 0 start sleeping
main end
Thread-1runnable run
The Thread - 0 5 seconds sleep
Thread-0 over
The Thread - 1 began to sleep
Thread-1runnable exception:java.lang.InterruptedException: sleep interrupted
Thread-1 over

We can see interrupted and did not have an impact on access to the lock, and finally sleep method interrupt response.

Here is my blocking interrupted lockInterruptibly local analog ():

 1 public class ReentrantLockInterruptableDemo {
 2     public static void main(String[] args) throws InterruptedException {
 3         System.out.println("main start");
 4         Thread thread1 = new Thread(new LockThreadInterruptableDemo());
 5         Thread thread2 = new Thread(new LockThreadInterruptableDemo());
 6         thread1.start();
 7         Thread.sleep(1000); // 确保thread1获取到了锁
 8         thread2.start(); // 此时thread2处于获取锁的阻塞状态
 9         thread2.interrupt();
10         System.out.println("main end");
11     }
12 }
13 
14 class LockThreadInterruptableDemo implements Runnable {
15     public static ReentrantLock lock = new ReentrantLock();
16     @Override
17     public void run() {
18         System.out.println(Thread.currentThread().getName() + "runnable run");
19         try {
20             lock.lockInterruptibly();
21             System.out.println(Thread.currentThread().getName() + "开始睡眠");
22             Thread.sleep(5000);
23             System.out.println(Thread.currentThread().getName() + "睡了5秒");
24         } catch (Exception e) {
25             System.out.println(Thread.currentThread().getName() + "runnable exception:" + e);
26         } finally {
27             try {
28                 lock.unlock();
29             } catch(IllegalMonitorStateException E) {
 30                  System.out.println ( "thread by" + Thread.currentThread () getName () + " interrupted prematurely cause not acquired lock." );
 31 is              }
 32          }
 33 is          System.out.println (the Thread . .currentThread () getName () + "over" );
 34 is      }
 35 }

The results are:

main start
Thread-0runnable run
The Thread - 0 start sleeping
main end
Thread-1runnable run
Thread-1runnable exception:java.lang.InterruptedException
Due to thread the Thread - 1 lead not get interrupted in advance to lock
Thread-1 over
The Thread - 0 5 seconds sleep
Thread-0 over

Conclusion

For interrupt processing thread is relatively common, particularly in relation to the framework of multi-threaded component. The ability to handle a variety of situations thread interrupted, will reflect the situation for a skilled programmer to master multi-threaded. Little progress every day, a Japanese soldier arch, come on!

 

Guess you like

Origin www.cnblogs.com/zzq6032010/p/10925853.html