如何停止线程?

停止线程思路

  1. 使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。
  2. 使用stop方法强行终止线程(这个方法不推荐使用,因为stop和suspend、resume一样,也可能发生不可预料的结果)。
  3. 使用interrupt方法中断线程。(表示让当前等待的线程直接抛出异常)

代码如下:

package com.newDemo.controller.test;

class stopThread extends Thread{
	private volatile boolean flag = true;
	
	public void run(){
		System.out.println("子线程开始....");
		while (flag) {
			try {
				wait();
			} catch (InterruptedException e) {
				// e.printStackTrace();
				stopThread();
			}
		}
		System.out.println("子线程结束....");
	}
	
	public void stopThread() {
		flag = false;
	}
}

public class threadDemo19 {
	
	public static void main(String[] args) {
		stopThread stopThread = new stopThread();
		stopThread.start();
		for (int i = 1; i < 10; i++) {
			try {
				Thread.sleep(1000);
				System.out.println("i:" + i);
				if (i == 8) {
					// stopThread.stopThread();
					//表示让当前等待的线程直接抛出异常
					stopThread.interrupt();
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		}

	}

}

这样的话,就能够让当前子线程停止,但是主线程还在继续,所以这个时候要注意,不要以为代码是错误的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值