外部線程停止Java子線程的方法


一、Thread.stop()
官方不推薦,Because it is inherently unsafe.


二、方式一
1. 線程類示例

public class ThreadT1 implements Runnable {
    private Thread threadThis;

    public void start() {
        threadThis = new Thread(this);
        threadThis.start();
    }

    public void stop() {
        threadThis = null;
    }

    public void run() {
        Thread thisThread = Thread.currentThread();
        while (threadThis == thisThread) {
        System.out.println("lalala~ ");
        // DO YOUR WORK !
    }
    System.out.println("stopped!!!");
    }
}
            


2. 使用示例

ThreadT1 th1 = new ThreadT1();
th1.start(); //新建線程並啟動
th1.stop(); //停止這個線程


三、方式二
1. 線程類示例

public class ThreadT2 extends Thread {
    private boolean stop = false;

    public void stopByMark() {
        stop = true;
    }

    public void run() {
        while (!stop) {
        System.out.println("lalala~ ");
        // DO YOUR WORK !
    }
    System.out.println("stopped!!!");
    }

}


2.使用示例

ThreadT2 th2 = new ThreadT2();
th2.start(); //新建線程並啟動
th2.stopByMark(); //停止這個線程


附、關於Thread.interrupt()
通過這個方式也能停止線程。
前提條件:

public void run(){
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) { //必須存在捕獲InterruptedException的方法,且發生了該    拋出就調用stop方法。
    e.printStackTrace();
    stopByMark();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM