多线程的中断机制

协作式中断:一个线程不应该由其他线程来强制中断或停止,而是应该由线程自己自行中断。这样才更加安全可靠。

每个线程都维护了一个中断标识,当标识被标记成中断之后,线程会在适当的时间节点执行中断操作。

线程A在执行,然后线程B在某个时刻通知线程A适当时刻执行中断操作(调用A的interrupt()方法),则线程A则在适当时刻进行中断
(线程A如果在运行状态,则需要检测中断标识,从而判断是否需要中断,调用本线程的isInterrupted()方法;
如果线程A为阻塞或者等待状态,则无需检测,内部会自动检测。
ps:如果是睡眠状态的中断,由于内部中断之后会清除中断标识,因此如果是根据循环来检测中断标识,需要再次设置中断标识,这样才可以跳出循环)

public static void main(String[] args) {
    
    
	Thread tA = new Thread(() -> {
    
    
		while (!Thread.currentThread().isInterrupted()) {
    
    
			System.out.println("running...");
			try {
    
    
				Thread.currentThread().sleep(200);
			} catch (InterruptedException e) {
    
    
				System.out.println(Thread.currentThread().isInterrupted());
				// 需再次设置中断标识
				Thread.currentThread().interrupt();
				System.out.println("tA has stoped!");
			}
		}
	});
	tA.start();
	try {
    
    
		Thread.currentThread().sleep(2000);
	} catch (InterruptedException e) {
    
    
		e.printStackTrace();
	}
	tA.interrupt();
}

猜你喜欢

转载自blog.csdn.net/weixin_43871678/article/details/111658142