多线程中interrupt的注意事项

在很久很久以前,线程的停止是依赖于stop方法,但是使用过程中出现了安全问题,以及很多预料不到的情况,所以被抛弃了,而现在加入interrupt方法来停止线程,而这个方法的意义就是"中断",但是用来并没有那么简单:

官方中文文档解释:

看了半天可能也不太知道个所以然来;

首先一点直接使用interrupt是中断不了run方法里面运行的代码的它会继续执行了,除了文档里面提及的

 这个你一下理解不了,接下来端上代码示范:

public class MyThread implements Runnable{

	@Override
	public void run() {
		// TODO Auto-generated method stub
			System.out.println(Thread.currentThread().getName()+"start");
			for(int i=0;i<100;i++) {
				System.out.println(Thread.currentThread().getName()+":"+i);
			}
			System.out.println(Thread.currentThread().getName()+"end");
	}

}
public class MyRun {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(Thread.currentThread().getName()+"start");
		MyThread thread=new MyThread();
		Thread t1=new Thread(thread);
		t1.start();
		t1.interrupt();
		System.out.println("t1.isInterrupted():"+t1.isInterrupted());
		System.out.println("t1.isAlive():"+t1.isAlive());
		for(int i=0;i<100;i++) {
			System.out.println(Thread.currentThread().getName()+":"+i);
		}
		System.out.println(Thread.currentThread().getName()+"end");
	}

}

 运行结果:

重点在判断线程是否中断的时候发现,线程是中断的,但是线程确是活着的,还在执行线程的方法;

那就说明线程并没有停止,它还在执行,那如何让它停下来呢?

主代码不变,运行结果:

 

但是我们还是得判断一下,是否线程真的停止,修改主代码如下:

运行结果:

在这里解释一下为什么在判断中断的时候是false:

因为现在线程已经结束了,那中断状态也会随之取消,也就相当于玩游戏死掉之后,数据重置一样!

猜你喜欢

转载自blog.csdn.net/qq_37909508/article/details/89101514