Home  >  Article  >  Java  >  Three ways to end a thread in java

Three ways to end a thread in java

小老鼠
小老鼠Original
2024-04-17 05:09:15411browse

The three ways to end a thread in Java are: use the stop() method (no longer recommended); use the interrupt() method to send an interrupt signal; use the join() method to let the main thread wait for the target Thread completed.

Three ways to end a thread in java

Three ways to end a thread in Java

In Java, there are many ways to end a thread. The three most commonly used methods are introduced below:

1. Use the stop() method

Note: The stop() method is no longer recommended Use because it will directly terminate the thread, possibly causing data corruption or other problems.

<code class="java">public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            // 线程任务
        });

        thread.start();
        thread.stop();
    }
}</code>

2. Use the interrupt() method

The interrupt() method will send an interrupt signal to the thread, and the thread can check Thread.interrupted() To determine whether an interrupt signal has been received.

<code class="java">public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            while (!Thread.interrupted()) {
                // 线程任务
            }
        });

        thread.start();
        thread.interrupt();
    }
}</code>

3. Use the join() method

The join() method will cause the main thread to wait for the target thread to complete execution. When the target thread is completed, the main thread will continue execution.

<code class="java">public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            // 线程任务
        });

        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}</code>

The above is the detailed content of Three ways to end a thread in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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