Writing in the front

When we call the Wait () method of a Java object or the sleep() method of a thread, we need to catch and handle InterruptedException. If we mishandle InterruptedException, unexpected consequences can occur! Today, we will use a case study to explain in detail why threads that interrupt execution do not work.

The article has been included: github.com/sunshinelyz… And gitee.com/binghe001/t…

Application case

For example, in the following program code, the InterruptedTask class implements the Runnable interface, gets a handle to the current thread in the run() method, and checks whether the current thread has been interrupted through the isInterrupted() method in the while(true) loop. The while(True) loop exits if the current Thread is interrupted, along with a line of Thread.sleep(100) code that catches InterruptedException. The entire code is shown below.

package io.binghe.concurrent.lab08;

/ * * *@author binghe
 * @version 1.0.0
 * @descriptionThread test interrupt */
public class InterruptedTask implements Runnable{

    @Override
    public void run(a) {

        Thread currentThread = Thread.currentThread();
        while (true) {if(currentThread.isInterrupted()){
                break;
            }

            try {
                Thread.sleep(100);
            } catch(InterruptedException e) { e.printStackTrace(); }}}}Copy the code

The intent of the above code is to check if the thread has been interrupted with the isInterrupted() method and exit the while loop if it has. Other threads by calling thread of execution of interrupt () method to interrupt execution threads, this will set the interrupt flag bit of thread of execution, so that the currentThread. IsInterrupted () returns true, so you can exit the while loop.

That doesn’t seem to be a problem! But is it really true? We create an InterruptedTest class for testing, as shown below.

package io.binghe.concurrent.lab08;

/ * * *@author binghe
 * @version 1.0.0
 * @descriptionTest thread interrupt */
public class InterruptedTest {
    public static void main(String[] args){
        InterruptedTask interruptedTask = new InterruptedTask();
        Thread interruptedThread = new Thread(interruptedTask);
        interruptedThread.start();
        try {
            Thread.sleep(1000);
        } catch(InterruptedException e) { e.printStackTrace(); } interruptedThread.interrupt(); }}Copy the code

We run the main method, as shown below.

This is not what we expected! Not the same! Not the same! Why is that?

Problem analysis

The above code explicitly calls the thread’s interrupt() method to interrupt the thread, but it does nothing. The reason is that the thread’s run() method blocks most of the time on sleep(100). When other threads interrupt the thread by calling interrupt(), InterruptedException is most likely triggered. While trigger InterruptedException, the JVM will remove interrupt flag bit of thread at the same time, so, this time in the run () method of judging the currentThread. The isInterrupted () returns false, I would not exit the current while loop.

Now that the problem analysis is cleared, how do I interrupt the thread and exit the program?

Problem solving

The correct way to do this is to reset the interrupt flag bit after catching the exception in the while(true) loop in the Run () method of the InterruptedTask class, so the correct code for the InterruptedTask class is shown below.

package io.binghe.concurrent.lab08;

/ * * *@author binghe
 * @version 1.0.0
 * @descriptionInterrupt thread test */
public class InterruptedTask implements Runnable{

    @Override
    public void run(a) {

        Thread currentThread = Thread.currentThread();
        while (true) {if(currentThread.isInterrupted()){
                break;
            }

            try {
                Thread.sleep(100);
            } catch(InterruptedException e) { e.printStackTrace(); currentThread.interrupt(); }}}}Copy the code

You can see that we have added a new line to the catch block that catches InterruptedException.

currentThread.interrupt();
Copy the code

This allows us to reset the thread’s interrupt flag after catching InterruptedException, thereby interrupting the currently executing thread.

We run the Main method of the InterruptedTest class again, as shown below.

conclusion

Use caution when handling InterruptedException. If InterruptedException is thrown when the thread of execution is interrupted by calling InterruptedException, The JVM also clears the interrupt flag of the executing thread and returns false when isInterrupted() is invoked. The correct response is to catch InterruptedException in the run() method of the thread of execution and reset the interrupt flag bit (in the catch block that catches InterruptedException, Reinvoke the interrupt() method of the current thread.

Ok, that’s enough for today. I’m Glacier. See you next time

Glacier Original PDF

Follow Glacier Technology wechat official account:

Reply to “Concurrent Programming” to receive the PDF of In-depth Understanding of High Concurrent Programming (1st edition).

Reply “concurrent source code” to get the “Concurrent programming core Knowledge (source code Analysis first edition)” PDF document.

Reply to “Limit Traffic” to get the PDF document “Distributed Solution under 100 million Traffic”.

Reply to “design patterns” to get the PDF of “simple Java23 design patterns”.

Reply “new Java8 features” obtain the Java8 new features tutorial PDF document.

Reply to “Distributed Storage” to receive the PDF of “Learn Distributed Storage Techniques from Glacier”.

Reply to “Nginx” to receive the PDF of Learn Nginx Technology from Glacier.

Reply to “Internet Engineering” to get the PDF of “Learn Internet Engineering techniques from Glacier”.

Big welfare

WeChat search the ice technology WeChat 】 the public, focus on the depth of programmers, daily reading of hard dry nuclear technology, the public, reply within [PDF] have I prepared a line companies interview data and my original super hardcore PDF technology document, and I prepared for you more than your resume template (update), I hope everyone can find the right job, Learning is a way of unhappy, sometimes laugh, come on. If you’ve worked your way into the company of your choice, don’t slack off. Career growth is like learning new technology. If lucky, we meet again in the river’s lake!

In addition, I open source each PDF, I will continue to update and maintain, thank you for your long-term support to glacier!!

Write in the last

If you think glacier wrote good, please search and pay attention to “glacier Technology” wechat public number, learn with glacier high concurrency, distributed, micro services, big data, Internet and cloud native technology, “glacier technology” wechat public number updated a large number of technical topics, each technical article is full of dry goods! Many readers have read the articles on the wechat public account of “Glacier Technology” and succeeded in job-hopping to big factories. There are also many readers to achieve a technological leap, become the company’s technical backbone! If you also want to like them to improve their ability to achieve a leap in technical ability, into the big factory, promotion and salary, then pay attention to the “Glacier Technology” wechat public account, update the super core technology every day dry goods, so that you no longer confused about how to improve technical ability!