search
HomeJavajavaTutorialInterruption and termination of threads in java

Interruption and termination of threads in java

Nov 27, 2019 pm 02:15 PM
javainterruptthreadtermination

Interruption and termination of threads in java

Interruption and termination of threads

1、interrupt()isInterrupted()、## The role of #interrupted()

Interrupt is an identification bit of a thread. It indicates whether a running thread has been interrupted by other threads. Other threads can call the thread's # The ##interrupt()

method interrupts it. The thread can determine whether it has been interrupted by calling the isInterrupted() method. The thread can also call the of Thread interrupted()Static method resets the interrupt flag bit of the current thread. Related video tutorial recommendations:

java online video

Note: Do not think that the thread will stop when the interrupt() method of the thread is called, it just Made a sign.

As follows:

public class InterruptThread extends Thread{
    @Override
    public void run() {
        //一个死循环
        while (true){
            System.out.println("InterruptThread正在执行");
        }
    }
}

public static void main(String[] args) throws InterruptedException {
    InterruptThread interruptThread = new InterruptThread();
    interruptThread.start();
    interruptThread.interrupt();//调用线程的interrupt()
    System.out.println("interruptThread是否被中断,interrupt  = " + interruptThread.isInterrupted());
    //此时isInterrupted()方法返回true
}

输出结果:
interruptThread是否被中断,interrupt  = true
InterruptThread正在执行
InterruptThread正在执行
InterruptThread正在执行
//...

You can see that when you call the interrupt() method of the thread, calling the isInterrupted() method will return true, but the thread will still continue. Carry on. So how can we terminate the running of a thread?

2. Terminate the running of the thread

A thread will automatically end after executing the run method normally. If an exception occurs during the running process, it will also end early; so use In these two cases, we can also safely terminate the running thread in the following three ways:

2.1. Using the interrupt flag bit

The interrupt mentioned earlier The operation can be used to cancel the thread task, as follows:

public class InterruptThread extends Thread{
    @Override
    public void run() {
        while (!isInterrupted()){//利用中断标记位
            System.out.println("InterruptThread正在执行");
        }
    }
}

When there is no need to run the InterruptThread thread, by calling InterruptThread.interrupt() so that isInterrupted() returns true, the thread can exit the loop and the normal execution is completed. It ends automatically after that.

2.2. Using a boolean variable

Using a boolean variable is the same as the above method, as follows:

public class InterruptThread extends Thread{
    
    private volatile boolean isCancel;

    @Override
    public void run() {
        while (!isCancel){//利用boolean变量
            System.out.println("InterruptThread正在执行");
        }
    }

    public void cancel(){
        isCancel = true;
    }
}

When there is no need to run the InterruptThread thread By calling InterruptThread.cancel() to make isCancel equal to true, the thread can exit the loop and end automatically after normal execution. Note here that the boolean variable must be modified with volatile to ensure the visibility of the memory.

2.3. Respond to InterruptedException

When interrupting a thread by calling its interrupt(), if the thread is blocked, waiting for a limited time, or waiting indefinitely, Then an InterruptedException will be thrown, thus ending the thread early. For example, when you call the Thread.sleep() method, you will usually be asked to catch an InterruptedException, as follows:

public class InterruptThread extends Thread{
    @Override
    public void run() {
        try{
            while (true){
                Thread.sleep(100);//Thread.sleep会抛出InterruptedException
                System.out.println("InterruptThread正在执行");
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}

When there is no need to run the InterruptThread thread , by calling InterruptThread.interrupt() to cause Thread.sleep() to throw InterruptedException, the thread can exit the loop and end early. Before throwing an InterruptedException, the JVM will reset the interrupt flag bit, and the calling thread's isInterrupted() method will return false.

Recommended java related articles and tutorials:

Introduction to java programming

The above is the detailed content of Interruption and termination of threads in java. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor