第六章:并发编程-取消与关闭

线程中断是一种协作机制,线程可以通过这种机制来通知另一个线程,告诉它在合适的或者可能的情况下停止当前工作,并转而执行其他的工作。

每一个线程都有一个boolean类型的终端状态。当中断线程时,这个线程的终端状态将被设置为true。在Thread中包含了终端线程以及查询线程中断状态的方法。

interrupt方法能中断目标线程。

isInterrupted方法能返回目标线程的终端状态。

静态的interrupted方法将清除当前线程的终端状态,并返回之前的值,这也是清除终端状态的唯一方法。

中断操作:不会真正地中断一个正在运行的线程,而是发出中断请求,然后由线程在下一个合适的时刻中断自己。

import java.math.BigInteger;
import java.util.concurrent.BlockingQueue;

public class PrimeProducer extends Thread{
	
	private final BlockingQueue<BigInteger> queue;

	public PrimeProducer(BlockingQueue<BigInteger> queue) {
		this.queue = queue;
	}
	
	public void run(){
		try {
			BigInteger p = BigInteger.ZERO;
			while (!Thread.currentThread().isInterrupted()) {
				queue.put( p = p.nextProbablePrime());
			}
		} catch (Exception e) {
			
		}
	}
	
	public void cancel(){
		interrupt();
	}
	
}

中断策略:

    最合理的中断策略是某种形式的线程级取消操作或者服务级取消操作:尽快退出,在必要时进行清理,通知某个所有者该线程已经退出。

响应中断:

    有两种方式处理InterruptedException

  • 传递异常,从而使你的方法也称为可中断的阻塞方法。
  • 恢复中断状态,从而使调用栈中的上层代码能够对其进行处理。

    

猜你喜欢

转载自blog.csdn.net/dxh0823/article/details/80040663