如何停止线程
解决方案
创建一个线程:
public class StopThread extends Thread {
private volatile boolean finished = false;
@Override
public void run() {
while (!finished && !Thread.currentThread().isInterrupted()) {
try {
System.out.println(Thread.currentThread().getName() + " is alive.");
TimeUnit.SECONDS.sleep(10);
System.out.println(Thread.currentThread().getName()+ " is over.");
} catch (InterruptedException e) {
e.printStackTrace();
finished = true;
break;
}
}
}
public void shutdown() {
this.finished = true;
}
public void shutdownWithInterrupt(){
this.finished = true;
interrupt();
}
}
测试:
public class StopThreadTest {
public static void main(String[] args) throws InterruptedException {
StopThread stopThread = new StopThread();
stopThread.start();
TimeUnit.SECONDS.sleep(3);
System.out.println("stopThread is going to be shutdown");
// stopThread.shutdownWithInterrupt();
stopThread.shutdown();
System.out.println(Thread.currentThread().getName() + " thread is over...");
}
}
结果:
Thread-0 is alive.
stopThread is going to be shutdown
main thread is over...
Thread-0 is over.
可以发现stopThread
并没有停止下来,因为此时的stopThread
正在睡眠,在睡眠结束之后,会继续执行Thread-0 is over.
。因为里这stopThread
中没有调用可中断方法,如(join,sleep,wait)
***对于这种情况,正确停止线程方法:即调用stopThread.shutdownWithInterrupt()
***
结果:
Thread-0 is alive.
stopThread is going to be shutdown
main thread is over...
java.lang.InterruptedException: sleep interrupted
at java.base/java.lang.Thread.sleep(Native Method)
at java.base/java.lang.Thread.sleep(Thread.java:335)
at java.base/java.util.concurrent.TimeUnit.sleep(TimeUnit.java:446)
at com.java.thread.StopThread.run(StopThread.java:14)
可以发现Thread-0 is over.
,并没有执行,线程被停止下来了!!