BlockingQueue与InterruptedException
感谢Blader同学的抛砖
首先,这段代码会编译成功吗,运行起来会有异常吗,他会打印什么?
import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class Foo { public static void main(String[] args) throws InterruptedException { BlockingQueue q = new LinkedBlockingQueue(); q.put(1); Thread.currentThread().interrupt(); System.out.println(q.take()); } }
运行后结果如下:
Exception in thread "main" java.lang.InterruptedException at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireInterruptibly(AbstractQueuedSynchronizer.java:1135) at java.util.concurrent.locks.ReentrantLock.lockInterruptibly(ReentrantLock.java:312) at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:354) at Foo.main(Foo.java:9)
看了一下源代码,阻塞队列的访问方法(take、put、poll、offer)会在执行之前检查Lock对象的中断标记,而Lock对象则是检查当前线程的中断标记