Home > Java > javaTutorial > body text

How to stop terminating thread in Java?

PHPz
Release: 2024-04-11 14:33:02
Original
838 people have browsed it

There are four ways to stop and terminate a thread in Java: interrupt() method: interrupt the thread and throw an InterruptedException exception. stop() method: Not recommended as it stops the thread immediately, possibly resulting in data loss. Set interrupt flag: Set a flag for the thread to poll to determine whether it needs to be terminated. Using join(): Blocks the current thread until the thread calling join() from another thread terminates.

How to stop terminating thread in Java?

How to stop terminating threads in Java

In Java, threads can be terminated in many ways. Understanding how to properly terminate threads is critical to ensuring application stability and performance. This article will discuss common methods of stopping and terminating threads, with practical cases attached.

Method 1: interrupt() method

interrupt() method can be used to interrupt the execution of a thread. If the thread is sleeping or waiting for I/O, you will receive an InterruptedException exception. In the following practical case, we use the interrupt() method to stop a sleeping thread:

public class InterruptThreadExample {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(10000); // 睡 10 秒
            } catch (InterruptedException e) {
                System.out.println("已中断!");
            }
        });

        thread.start();
        Thread.sleep(1000); // 睡 1 秒

        thread.interrupt();
        thread.join(); // 等待线程终止
    }
}
Copy after login

Output:

已中断!
Copy after login

Method 2: stop() method

The stop() method is not recommended because it stops the thread immediately, possibly causing data loss or application instability. It is strongly recommended to use the interrupt() method instead.

Method 3: Set the interrupt flag

You can set an interrupt flag for threads to poll. When this flag is set to true, the thread knows that it should terminate:

public class InterruptFlagExample {

    private volatile boolean interrupted = false;

    public static void main(String[] args) throws InterruptedException {
        InterruptFlagExample example = new InterruptFlagExample();

        Thread thread = new Thread(() -> {
            while (!example.isInterrupted()) {
                // 做一些事情
            }
        });

        thread.start();
        Thread.sleep(1000); // 睡 1 秒

        example.setInterrupted(true);
        thread.join(); // 等待线程终止
    }

    public void setInterrupted(boolean interrupted) {
        this.interrupted = interrupted;
    }

    public boolean isInterrupted() {
        return interrupted;
    }
}
Copy after login

Method 4: Using Join

join() method can be used to stop and wait for the thread to terminate . It will block the current thread until another thread that calls join() terminates.

public class JoinExample {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(10000); // 睡 10 秒
            } catch (InterruptedException e) {}
        });

        thread.start();
        thread.join(); // 等待线程终止
    }
}
Copy after login

This blocks the current thread for 10 seconds until the other thread terminates.

The above is the detailed content of How to stop terminating thread in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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