阻塞操作不可取消

public class BlockedInterrupteTest extends Thread{

    private final BlockingQueue<BigInteger> queue;
    private volatile boolean cancelled = false;

    BlockedInterrupteTest(BlockingQueue<BigInteger> queue){
        this.queue = queue;
    }
    
    public void run() {
        try {
            BigInteger p = BigInteger.ONE;
            while(!cancelled){
                queue.put(p = p.nextProbablePrime());
            }
        }catch (InterruptedException e){}
    }
    
    public void cancel() {
        cancelled = true;
    }
}

BlockingQueue是阻塞队列,它的put操作会在队列满时一直阻塞。

/**
 * Inserts the specified element into this queue, waiting if necessary
 * for space to become available.
 *
 * @param e the element to add
 * @throws InterruptedException if interrupted while waiting
 * @throws ClassCastException if the class of the specified element
 *         prevents it from being added to this queue
 * @throws NullPointerException if the specified element is null
 * @throws IllegalArgumentException if some property of the specified
 *         element prevents it from being added to this queue
 */
void put(E e) throws InterruptedException;

所以,当其他线程调cancel()函数时,如果当前线程执行queue.put(p = p.nextProbablePrime()); 阻塞了,是无法停止当前线程的。

解决办法是使用线程中断来替代自定义的取消标识:

public void run() {
    try {
        BigInteger p = BigInteger.ONE;
        while(!Thread.currentThread().isInterrupted()){
            queue.put(p = p.nextProbablePrime());
        }
    }catch (InterruptedException e){}
}

public void cancel() {
    interrupt();
}

即使put是阻塞的,也会响应线程中断,从而达到取消操作的目的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值