一旦线程被中断,如何完全停止?

时间:2014-06-01 19:34:02

标签: java multithreading interrupt

在我当前的代码中,我正在创建一个实现runnable的线程。我在主要开始它然后让主要中断它。然而,一旦它被打断它继续运行。我希望线程完全停止。

线程类:

public class MyThread implements Runnable {

    @Override
    public void run() {

        // string relating to the threads name
        // Note that you actually set the threads name in the main
        String threadName = Thread.currentThread().getName();


        System.out.println(threadName + " is now started...");

        System.out.println(threadName + " about to count down...");

        for (int loop = 100; loop > 1; loop--) {

            try {           
                //for 0.5 seconds
                Thread.sleep(500);      
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println(threadName + " was Interupted!");        
            }               

            System.out.println(loop);
        }           

    }

}

主:

public class Runner {

    public static void main(String[] args) {

        //Create thread from class
        MyThread myt= new MyThread();

        //Passing in the thread from class and also naming it
        Thread t= new Thread(myt, "My Thread");

        //Actually starts the thread
        t.start();

        //Main thread has a sleep for 5 seconds then interrupts t
        try {
            Thread.sleep(5000);
            t.interrupt();
            System.out.println("Interupting...");
        } catch (InterruptedException e) {
            e.printStackTrace();                
        }       

    }

}

输出(注意线程如何不停止):

My Thread is now started...
My Thread about to count down...
100
99
98
97
96
95
94
93
92
Interupting...
java.lang.InterruptedException: sleep interrupted
My Thread was Interupted!
91
    at java.lang.Thread.sleep(Native Method)
    at threads.MyThread.run(MyThread.java:22)
    at java.lang.Thread.run(Unknown Source)
90
89
88
87
86
85

4 个答案:

答案 0 :(得分:3)

只有break离开循环:

catch (InterruptedException e) {
    e.printStackTrace();
    System.out.println(threadName + " was Interupted!");
    Thread.currrentThread().interrupt();
    break;
}

答案 1 :(得分:2)

boolean方法中执行任何操作之前,只需使用将要检查的run()标志,并根据其状态执行所需操作。确保它应该是volatile

只需致电myt.setRunning(false)而不是t.interrupt()

示例cde:

class MyThread implements Runnable {

    private volatile boolean isRunning=true;

    @Override
    public void run() {             

        for (int loop = 100; loop > 1; loop--) {                 

            if(!isRunning){
               // break or do whatever is needed here
            }             
        }    
    }               

}

答案 2 :(得分:0)

只需正确编写run()方法,以便在中断时突破循环,而不是仅仅继续。

线程确实有一个stop()方法,但由于某种原因,它已被弃用;它可以使事物处于不一致且可能不稳定的状态。不要使用它!

答案 3 :(得分:0)

对于这样的重复任务,您还可以使用TimerTask

请注意,此代码不会停止为零。

public class CountdownTask extends TimerTask {

    private int from;

    public CountdownTask(int from) {
        this.from = from;
    }

    @Override
    public void run() {
        System.out.println(from--);
    }
}

private void example() throws InterruptedException {
    Timer timer = new Timer("Countdown");
    timer.schedule(new CountdownTask(100), 0, 500);
    Thread.sleep(2000); //do something
    timer.cancel(); //stop task
}