简体   繁体   English

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

[英]How to completely stop a thread once it has been interrupted?

In my current code I am creating a thread that implements runnable . 在当前代码中,我正在创建一个实现runnable的线程。 I am starting it in the main then letting the main interrupt it. 我从主启动它,然后让主打断它。 However it once it is interrupted it continues to run. 但是,一旦被中断,它将继续运行。 I would like the thread to completely stop. 我希望线程完全停止。

Thread Class: 线程类:

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

    }

}

Main: 主要:

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

    }

}

Output (note how thread does not stop): 输出(注意线程如何不停止):

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

Just break out of the loop: 只是break循环:

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

Simply use a boolean flag that will be checked before doing any operation in the run() method and based on its state do whatever is needed. 只需使用一个boolean标志,该标志将在run()方法中执行任何操作之前检查,并根据其状态执行所需的任何操作。 Make sure it should be volatile . 确保它应该是volatile

simply call myt.setRunning(false) instead of t.interrupt() 只需调用myt.setRunning(false)而不是t.interrupt()

Sample cde: 示例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
            }             
        }    
    }               

}

Just write the run() method correctly, so that it breaks out of the loop when interrupted, rather than just continuing. 只要正确地编写run()方法,即可使其在中断时脱离循环,而不仅仅是继续。

Thread does have a stop() method , but it's deprecated for a reason; 线程确实具有stop()方法,但出于某种原因不建议使用; it can leave things in an inconsistent and potentially unstable state. 它将使事物处于不一致甚至潜在的不稳定状态。 Don't use it! 不要使用它!

For such a repeating task you could also use a TimerTask : 对于这样的重复任务,您还可以使用TimerTask

Just note this code won't stop at zero. 请注意,此代码不会从零停止。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM