如何正确的停止一个线程

通常定义一个标记,来判断标记的状态停止线程的执行

/**
 * @author VicterTian
 * @version V1.0
 * @Date 2018/12/11
 */
public class ThreadTest09 {
	public static void main(String[] args) {
		//Runnable r1 = new Processor();
		Processor r1 = new Processor();
		Thread t1 = new Thread(r1, "t1");
		t1.start();
		try {
			Thread.sleep(2000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//停止线程
		System.out.println("开始停止线程");
		r1.setFlag();
	}
}

class Processor implements Runnable {
	//线程停止标记,true为停止
	private Boolean flag = true;
	public void run() {
		for (int i = 1; i < 100; i++) {
			try {
				Thread.sleep(1000);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (flag) {
				System.out.println(Thread.currentThread().getName() + "," + i);
			}else{
				break;
			}
		}
	}
	void setFlag() {
		this.flag = false;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
正确停止一个线程,可以通过设置一个标志位,在需要停止线程的时候将标志位设置为True,然后在线程内部不断检查这个标志位,如果发现标志位为True,则退出线程。 以下是一个不停输出信息的线程的示例代码: ```python import threading import time class OutputThread(threading.Thread): def __init__(self): super(OutputThread, self).__init__() self.stopped = False def run(self): while not self.stopped: print("正在计算,请等待...") time.sleep(1) def stop(self): self.stopped = True ``` 接下来,我们可以创建一个模拟计算的线程,当这个线程运行一定时间后,就会停止输出线程。 以下是示例代码: ```python class CalcThread(threading.Thread): def __init__(self, output_thread, duration): super(CalcThread, self).__init__() self.output_thread = output_thread self.duration = duration def run(self): # 模拟计算 time.sleep(self.duration) # 停止输出线程 self.output_thread.stop() ``` 最后,我们可以通过创建一个输出线程一个计算线程,并启动它们来测试我们的代码: ```python if __name__ == '__main__': output_thread = OutputThread() calc_thread = CalcThread(output_thread, 5) output_thread.start() calc_thread.start() calc_thread.join() output_thread.join() print("程序结束") ``` 在这个示例中,我们创建了一个输出线程一个计算线程,输出线程会不断输出"正在计算,请等待...",而计算线程会模拟计算5秒钟后停止输出线程。最后,我们等待计算线程和输出线程运行结束,并输出"程序结束"。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值