java使用interrupt()终止线程

java使用interrupt终止线程

调用一个线程的interrupt() 方法中断一个线程,并不是强行关闭这个线程,只是将线程的中断状态置为true,线程是否中断,由线程本身决定。
isInterrupted() 判定当前线程是否处于中断状态。

使用interrupt()方法来中断线程的场景:
一般run()方法执行完,线程就会正常结束,有些线程它们需要长时间的运行,只有在外部某些条件满足的情况下,才能关闭这些线程。

public class InterrputTest {
	

	private static class InterrputThread extends Thread{
		


		@Override
		public void run() {
			while(!isInterrupted()){
				try {
					System.out.println("do bussiness");//线程非阻塞时,main调用线程的interrupt()方法,调用完之后中断状态为true,下次进入循环跳出,结束线程
					Thread.sleep(1000);//线程阻塞时,main调用线程的interrupt()方法,抛出InterruptedException异常,调用完之后会复位中断状态为false,catch中重新调用interrupt()才能跳出循环
				} catch (InterruptedException e) {
					e.printStackTrace();
					interrupt();//也可以使用break跳出循环;
				}
			}
		}
	}

	public static void main(String[] args) throws InterruptedException {
		Thread endThread = new InterrputThread();
		endThread.start();
		Thread.sleep(500);//主线程休眠500毫秒
		endThread.interrupt();
	}

}

猜你喜欢

转载自blog.csdn.net/z278785324/article/details/84661439