如何停止一个线程

如何停止线程

解决方案

创建一个线程:

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.,并没有执行,线程被停止下来了!!

发布了76 篇原创文章 · 获赞 66 · 访问量 51万+

猜你喜欢

转载自blog.csdn.net/u013887008/article/details/103266632