Home  >  Article  >  Java  >  What is a thread interrupt? Detailed introduction to Java thread interruption (with examples)

What is a thread interrupt? Detailed introduction to Java thread interruption (with examples)

不言
不言forward
2018-09-27 16:38:323107browse

This article brings you what is a thread interruption? The detailed introduction of Java thread interruption has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Everyone should be familiar with the broken code below. Thread sleep needs to catch or throw a thread interrupt exception, that is, someone suddenly rushes in and wakes you up while you are sleeping.

try {
    Thread.sleep(3000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

After the thread is interrupted at this time, the code will continue to run or throw an exception to end the run. This is not the role of the interrupted thread that we need.

What exactly is a thread interrupt?

Thread interruption means that the thread is interrupted by other threads while it is running. The biggest difference between it and stop is that stop forces the thread to be terminated by the system, while thread interruption sends an interrupt signal to the target thread. If the target thread does not receive the thread interrupt signal and terminate the thread, the thread will not terminate. Whether to exit or perform other logic is determined by the target thread.

Let’s take a look at the three most important methods of thread interruption. They all come from the Thread class!

1, java.lang.Thread#interrupt

Interrupt the target thread, send an interrupt signal to the target thread, and the thread is marked as interrupted.

2. java.lang.Thread#isInterrupted()

Determines whether the target thread is interrupted, and the interruption mark will not be cleared.

3.java.lang.Thread#interrupted

To determine whether the target thread is interrupted, the interrupt mark will be cleared.

Thread Interruption in Practice

Let’s demonstrate how to use thread interruption with an example!

Example 1 (interruption failed)

/**
 * 微信公众号:Java技术栈
 */
private static void test1() {
    Thread thread = new Thread(() -> {
        while (true) {
            Thread.yield();
        }
    });
    thread.start();
    thread.interrupt();
}

Will the thread in Example 1 be interrupted? Answer: No, because although an interrupt signal is sent to the thread, there is no logic in the program to respond to the interrupt signal, so the program will not react in any way.

Example 2: (Interruption successful)

/**
 * 微信公众号:Java技术栈
 */
private static void test2() {
    Thread thread = new Thread(() -> {
        while (true) {
            Thread.yield();

            // 响应中断
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("Java技术栈线程被中断,程序退出。");
                return;
            }
        }
    });
    thread.start();
    thread.interrupt();
}

We have added logic to respond to interrupts in Example 2. The program returns and exits after receiving the interrupt signal and printing out the information.

Example 3 (interruption failed)

/**
 * 微信公众号:Java技术栈
 */
private static void test3() throws InterruptedException {
    Thread thread = new Thread(() -> {
        while (true) {
            // 响应中断
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("Java技术栈线程被中断,程序退出。");
                return;
            }

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                System.out.println("Java技术栈线程休眠被中断,程序退出。");
            }
        }
    });
    thread.start();
    Thread.sleep(2000);
    thread.interrupt();
}

Example 3 sleep() method was interrupted and outputJava technology stack thread sleep was interrupted and the program exited . The program continues to run... why?

Let’s look at the source code of sleep:

What is a thread interrupt? Detailed introduction to Java thread interruption (with examples)

It can be seen that the interrupt mark will be cleared after the sleep() method is interrupted, so the loop will continue to run. .

Example 4 (interruption successful)

/**
 * 微信公众号:Java技术栈
 */
private static void test4() throws InterruptedException {
    Thread thread = new Thread(() -> {
        while (true) {
            // 响应中断
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("Java技术栈线程被中断,程序退出。");
                return;
            }

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                System.out.println("Java技术栈线程休眠被中断,程序退出。");
                Thread.currentThread().interrupt();
            }
        }
    });
    thread.start();
    Thread.sleep(2000);
    thread.interrupt();
}

Example 4 outputs all information and exits normally, just manually re-interrupt the current state after the sleep() method is interrupted and the mark is cleared Thread, then the program receives the interrupt signal and returns to exit.

Through the above four interrupt examples, I believe that we have a comprehensive understanding of the concept of Java thread interrupts.

The above is the detailed content of What is a thread interrupt? Detailed introduction to Java thread interruption (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete

Related articles

See more