Home > Java > javaTutorial > How to solve Java thread interrupt exception (InterruptedException)

How to solve Java thread interrupt exception (InterruptedException)

WBOY
Release: 2023-08-26 23:51:34
Original
1055 people have browsed it

How to solve Java thread interrupt exception (InterruptedException)

How to solve Java thread interruption exception (InterruptedException)

The thread interruption exception (InterruptedException) in Java is when a thread is waiting (sleep), waiting to acquire a lock ( Exceptions thrown by other threads during operations such as wait) and waiting for semaphores (signal). The occurrence of this exception means that the current thread is interrupted from the normal execution flow. In actual development, we need to handle this exception reasonably to ensure the stability and reliability of the program.

The main methods to solve Java thread interruption exceptions are as follows:

  1. Restore interruption status
    When a thread encounters a thread interruption exception, the exception will be thrown and Clear the interrupt status (clear the interrupt flag bit to zero). Before handling the exception, you can use the Thread.currentThread().isInterrupted() method to determine whether an interruption has occurred, and then decide whether to ignore the exception or perform further processing based on the specific situation. If you need to continue to maintain the interrupt status, you can call the Thread.currentThread().interrupt() method to reset the interrupt status before exception handling.

The following is a simple code example:

Thread thread = new Thread(() -> {
    try {
        // 线程执行一些耗时操作
        for (int i = 0; i < 10; i++) {
            System.out.println("执行中断操作 " + i);
            Thread.sleep(1000);
        }
    } catch (InterruptedException e) {
        // 捕获中断异常
        System.out.println("线程被中断了");
        // 恢复中断状态
        Thread.currentThread().interrupt();
    }
});

thread.start();

// 主线程休眠2秒后中断子线程
Thread.sleep(2000);
thread.interrupt();
Copy after login

In the above code, the child thread executes a loop, and each loop performs a time-consuming operation (sleep 1 second). The main thread sleeps for 2 seconds and then interrupts the child thread. When the child thread catches the interrupt exception, we use the interrupt() method to reset the interrupt status.

  1. Continue to throw exceptions to the upper layer
    Sometimes, we do not want to restore the interrupt state when an interrupt exception occurs, but we want to continue throwing exceptions to the upper layer. In this case, the exception can be thrown directly to the upper layer for processing.

The following is a sample code:

Thread thread = new Thread(() -> {
    try {
        // 线程执行一些耗时操作
        for (int i = 0; i < 10; i++) {
            System.out.println("执行中断操作 " + i);
            Thread.sleep(1000);
        }
    } catch (InterruptedException e) {
        // 直接向上层抛出异常
        throw new RuntimeException("线程中断异常", e);
    }
});

thread.start();

// 主线程休眠2秒后中断子线程
Thread.sleep(2000);
thread.interrupt();
Copy after login

In the above code, when the child thread catches the interrupt exception, we use throw new RuntimeException("Thread Interruption Exception" , e)Continue to throw exceptions to the upper layer.

  1. Exit gracefully
    In some cases, we want to exit gracefully after the thread is interrupted. In terms of implementation, you can add a flag bit to determine whether an interrupt has occurred and exit the thread at the appropriate time.

The following is a sample code:

class MyThread extends Thread {
    private volatile boolean isInterrupted = false;

    public void setInterrupted(boolean interrupted) {
        isInterrupted = interrupted;
    }

    @Override
    public void run() {
        try {
            // 线程执行一些耗时操作
            for (int i = 0; i < 10; i++) {
                if (isInterrupted) {
                    System.out.println("线程被中断了");
                    return;
                }
                System.out.println("执行中断操作 " + i);
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            System.out.println("线程被中断了");
            return;
        }
    }
}

MyThread thread = new MyThread();
thread.start();

// 主线程休眠2秒后中断子线程
Thread.sleep(2000);
thread.setInterrupted(true);
Copy after login

In the above code, we customized a thread class MyThread and added a isInterrupted flag. During the execution of the child thread, the flag bit is judged to determine whether to exit the thread.

To sum up, to solve Java thread interruption exceptions, you can restore the interruption status, continue to throw exceptions to the upper layer, or exit gracefully. The specific choice should be determined based on specific business needs and scenarios. Properly handling thread interrupt exceptions is an important part of ensuring program stability and reliability, and needs to be designed appropriately based on the actual situation.

The above is the detailed content of How to solve Java thread interrupt exception (InterruptedException). For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template