Home  >  Article  >  Java  >  How to use java interrupt() to interrupt blocking

How to use java interrupt() to interrupt blocking

WBOY
WBOYforward
2023-05-02 15:55:181580browse

Explanation

1. Calling interrupt() can interrupt blocking. Interrupting blocking does not mean the end of the thread's life cycle, but only interrupts the blocking state of the current thread.

2. Once interrupted in the blocking state, an InterruptedException exception will be thrown. This exception is like a signal to notify that the current thread has been interrupted.

Example

public static void main(String[] args) throws InterruptedException{
    Thread thread = new Thread(()->{
        try{
            TimeUnit.SECONDS.sleep(10);
        }catch (InterruptedException e){
            System.out.println("Thread is interrupted.");
        }
    });
    thread.start();
    TimeUnit.SECONDS.sleep(1);
    thread.interrupt();
}

The above is the detailed content of How to use java interrupt() to interrupt blocking. For more information, please follow other related articles on the PHP Chinese website!

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