多线程的终止

我们为什么需要线程终止?

  线程内代码执行完后,线程会自然进入死亡状态。但如果我们想要手动终止线程,该如何操作呢?

stop()/destroy()

  终止线程,Java面向对象的原则,最先想到的应该就是使用Thread类里的方法了吧。

  通过查看API,还真有线程的终止方法。但都由于方法有bug,而被弃用了。

  所以,不要使用!不要使用!不要使用!(致敬一下《三体》)
在这里插入图片描述
在这里插入图片描述

标志位法

  终止线程,通常的做法是提供一个boolean型的终止变量,当这个变量置为false,则终止线程的运行。

  我当年在大学写嵌入式开发时,竟无师自通地用了很多次。直接来个实例感受一下:

public class Test implements Runnable{
	
	private volatile boolean flag = true; //使用volatile修饰
	
	@Override
	public void run() {
		while(flag) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("线程:"+Thread.currentThread().getName()+" 在听歌");
		}
	}
	
	void terminate(){
		flag = false;
		System.out.println("线程:"+Thread.currentThread().getName()+" 终止了");
	}

	public static void main(String[] args) throws InterruptedException {
		
		Test t1 = new Test();
		Test t2 = new Test();
		new Thread(t1,"左耳朵").start();
		new Thread(t2,"右耳朵").start();
		
		Thread.currentThread().setName("手");
		
		for(int i=0;i<5;i++) {
			Thread.sleep(100);
			System.out.println("线程:"+Thread.currentThread().getName()+" 在CSND写笔记");
		}
		
		t1.terminate();//停止 左耳朵
		t2.terminate();//停止 右耳朵
		
	}
}

  其中flag使用volatile修饰符是为了保证数据的即时更新。《volatile修饰符》

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值