BlockingQueue与InterruptedException

GD Star Rating
loading...

感谢Blader同学的抛砖

首先,这段代码会编译成功吗,运行起来会有异常吗,他会打印什么?

  1. import java.util.concurrent.BlockingQueue;
  2. import java.util.concurrent.LinkedBlockingQueue;
  3.  
  4. public class Foo {
  5.    public static void main(String[] args) throws InterruptedException {
  6.        BlockingQueue q = new LinkedBlockingQueue();
  7.        q.put(1);
  8.        Thread.currentThread().interrupt();
  9.        System.out.println(q.take());
  10.    }
  11. }
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());
   }
}

运行后结果如下:

  1. Exception in thread "main" java.lang.InterruptedException
  2.     at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireInterruptibly(AbstractQueuedSynchronizer.java:1135)
  3.     at java.util.concurrent.locks.ReentrantLock.lockInterruptibly(ReentrantLock.java:312)
  4.     at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:354)
  5.     at Foo.main(Foo.java:9)
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对象则是检查当前线程的中断标记

原创内容,转载请注明: 转载自拈花微笑

本文链接地址: BlockingQueue与InterruptedException

685

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" extra="">

:wink: :-| :-x :twisted: :) 8-O :( :roll: :-P :oops: :-o :mrgreen: :lol: :idea: :-D :evil: :cry: 8) :arrow: :-? :?: :!:

使用新浪微博登陆

无觅相关文章插件,快速提升流量