首頁  >  文章  >  Java  >  Java如何停止終止執行緒?

Java如何停止終止執行緒?

PHPz
PHPz原創
2024-04-11 14:33:02787瀏覽

Java 中停止終止執行緒有四種方法:interrupt() 方法:中斷執行緒並引發 InterruptedException 例外。 stop() 方法:不建議使用,因為它會立即停止線程,可能導致資料遺失。設定中斷標誌:設定一個標誌,供線程輪詢判斷是否需要終止。使用 join():阻塞目前線程,直到另一個執行緒呼叫 join() 的執行緒終止。

Java如何停止終止執行緒?

Java 如何停止終止執行緒

在 Java 中,執行緒可以透過多種方式終止。了解如何正確終止執行緒對於確保應用程式穩定性和效能至關重要。本文將探討常用的停止終止執行緒的方法,並附帶實戰案例。

方法 1:interrupt() 方法

interrupt() 方法可用來中斷執行緒的執行。如果執行緒正在休眠或等待I/O,則會收到一個 InterruptedException 例外。在以下實戰案例中,我們使用interrupt() 方法來停止一個正在休眠的執行緒:

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(); // 等待线程终止
    }
}

輸出:

已中断!

方法2:stop() 方法

不建議使用stop() 方法,因為它會立即停止線程,可能導致資料遺失或應用程式不穩定。強烈建議使用 interrupt() 方法代替。

方法 3:設定中斷標誌

您可以設定一個中斷標誌,供執行緒輪詢。當標誌設為true 時,執行緒知道它應該終止:

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;
    }
}

方法4:使用Join

join() 方法可以用來停止和等待執行緒終止。它將阻塞當前線程,直到另一個線程調用了 join() 的線程終止。

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(); // 等待线程终止
    }
}

這會阻塞目前執行緒 10 秒,直到另一個執行緒終止。

以上是Java如何停止終止執行緒?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn