溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

java怎么停止線程

發(fā)布時間:2022-05-21 15:24:40 來源:億速云 閱讀:198 作者:iii 欄目:大數(shù)據(jù)

本文小編為大家詳細介紹“java怎么停止線程”,內(nèi)容詳細,步驟清晰,細節(jié)處理妥當,希望這篇“java怎么停止線程”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。

1、使用Interrupt來通知 

while (!Thread.currentThread().isInterrupted() && more work to do) {     do more work    }

首先通過 Thread.currentThread().isInterrupt() 判斷線程是否被中斷,隨后檢查是否還有工作要做。

public class StopThread implements Runnable {
 
    @Override
    public void run() {
 
        int count = 0;
 
        while (!Thread.currentThread().isInterrupted() && count < 1000) {
 
            System.out.println("count = " + count++);
 
        }
 
    }
 
    public static void main(String[] args) throws InterruptedException {
 
        Thread thread = new Thread(new StopThread());
        thread.start();
        Thread.sleep(5);
        thread.interrupt();
    }
 
}

2、使用volatile標志一個字段,通過判斷這個字段true/false退出線程

/**
 * 描述:     演示用volatile的局限:part1 看似可行
 */
public class WrongWayVolatile implements Runnable {
 
    private volatile boolean canceled = false;
 
    @Override
    public void run() {
        int num = 0;
        try {
            while (num <= 100000 && !canceled) {
                if (num % 100 == 0) {
                    System.out.println(num + "是100的倍數(shù)。");
                }
                num++;
                Thread.sleep(1);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) throws InterruptedException {
        WrongWayVolatile r = new WrongWayVolatile();
        Thread thread = new Thread(r);
        thread.start();
        Thread.sleep(5000);
        r.canceled = true;
    }
}

讀到這里,這篇“java怎么停止線程”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內(nèi)容的文章,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI