如何停止一个线程

如何停止线程

解决方案

创建一个线程:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值