问答详情
源自:3-3 Java线程停止广为流传的错误方法---interrupt方法

最后的思考题

所以除了设置状态标志,还有什么退出线程的方法呢???

提问者:我是猫_夏 2018-07-17 17:31

个回答

  • MrZhen
    2018-07-18 14:20:13
    已采纳

    在catch中再次调用interrupt()就OK了

  • tiger爱小狄
    2019-07-04 15:15:19

    也可以在catch中写一个 break;

  • 我爱孙佳怡
    2019-05-22 11:59:34

    在catch中加入interruput()后,有点不太明白,退出是能退出,但是Thread running少打印了一次啊

  • 慕先生0191147
    2018-08-23 10:07:06

    package imooc.concurrent;


    public class WrongWayStopThread extends Thread {

    public static void main(String[] args) {


    WrongWayStopThread thread = new WrongWayStopThread();

    System.out.println("Staring thread...");

    thread.start();


    try {

    Thread.sleep(3000);

    } catch (InterruptedException e) {

    e.printStackTrace();

    }

    System.out.println("Interrupting thread...");

    thread.interrupt();

    try {

    Thread.sleep(3000);

    } catch (InterruptedException e) {

    e.printStackTrace();

    }

    thread.keepRunning=false;


    System.out.println("Stopping application...");

    }


    public volatile boolean keepRunning = true;


    public void run() {


    while (keepRunning) {

    System.out.println("Thread is running...");

    long time = System.currentTimeMillis();

    while (System.currentTimeMillis() - time < 1000) {


    }


    }

    }

    }


  • MrZhen
    2018-07-18 14:31:01

    还有就是用try{}catch{}把while循环包起来