停止线程方法(interrupt)

这篇博客探讨了Java中停止线程的三种方法,重点讲解了推荐使用的interrupt()方法,它设置线程的中断标志,而不是直接停止线程。文章通过示例代码解释了如何正确使用interrupt(),并对比了isInterrupted()和interrupted()的区别,同时指出了stop()方法的安全隐患。
摘要由CSDN通过智能技术生成

java中有三种停止线程方法

1)使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。

2)使用stop方法方法强行终止线程,但是不推荐使用这个方法,应为stop不安全而且已经被废弃的方法,还有suspend和resume都是废弃的方法。

3)使用interrupt方法中断线程。

讲解第三种interrupt()方法 仅仅使房钱线程中打了一个停止的标记,并不是真的停止线程。代码如下:

public class MyThread extends Thread {
	@Override
	public void run() {
		super.run();
		for (int i = 0; i < 500000; i++) {
			System.out.println("i=" + (i + 1));
		}
	}
}
public class Run {

	public static void main(String[] args) {
		try {
			MyThread thread = new MyThread();
			thread.start();
			Thread.sleep(2000);
			thread.interrupt();
		} catch (InterruptedException e) {
			System.out.println("main catch");
			e.printStackTrace();
		}
	}

}

线程没有停止,而是打印完i

再分析下线程是否是停止的状态

this.interrupted() 测试当前线程是否已经中断。

this.isInterrupted()测试线程是否已经中断。

两者区别:(小白还是不懂,如果大神们知道还请您给我留个言解答下☺)

如下代码展示:

public class MyThread extends Thread {
	@Override
	public void run() {
		super.run();
		for (int i = 0; i < 50000; i++) {
			System.out.println("i=" + (i + 1));
		}
	}
}


public class Run {
	public static void main(String[] args) {
		try {
			MyThread thread = new MyThread();
			thread.start();
			Thread.sleep(1000);
			thread.interrupt();
			//Thread.currentThread().interrupt();
			System.out.println(thread.getName()+ " 是否停止1?="+thread.interrupted());
			System.out.println(thread.getName()+ " 是否停止2?=
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值