BlockingQueue在处理中断时会根据不同的操作进行不同的处理: 对于put操作,如果线程在插入元素时被中断,BlockingQueue会抛出InterruptedException异常,同时会将中断状态重新设置为true。 对于take操作,如果线程在获取元素时被中断,BlockingQueue也会抛出InterruptedException异常,同时会将中断状态重新设置为true。 因此,当使用Blocki...
@Overridepublicvoidrun() {while(true) {try{Integer el = blockingQueue.take();System.out.println(el);}catch(InterruptedException e) { } } } }); thread.start(); } } 两种解决方案 方案一:使用poll代替take,这将允许处理线程在等待一段时间而没有新输入时超时并终止。 publicclassBlackingQueueTest ...
publicfinalvoid await()throws InterruptedException { if (Thread.interrupted()) thrownew InterruptedException(); //加一个新的condition等待节点 Node node = addConditionWaiter(); //释放自己的锁 int savedState = fullyRelease(node); int interruptMode =0; while (!isOnSyncQueue(node)) { //如果当前线...
InterruptedException; /** * 入队一个元素,如果有空间则直接插入,并返回true; * 如果没有空间则等待timeout时间,插入失败则返回false */ boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException; /** * 出队一个元素,如果存在则直接出队,如果没有空间则一直阻塞等待 */ E take() ...
public E take() throws InterruptedException { final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { while (count == 0) //如果队列为空,那么在notEmpty对象上等待, //当put函数调用时,会调用notEmpty的notify进行通知。 notEmpty.await(); ...
publicvoidput(E e)throwsInterruptedException { if(e ==null)thrownewNullPointerException(); finalE[] items =this.items; finalReentrantLock lock =this.lock; lock.lockInterruptibly();//请求锁直到得到锁或者变为interrupted try{ try{ while(count == items.length)//如果满了,当前线程进入noFull对应的...
出队方法 take, 如果为空当前线程阻塞 publicEtake()throwsInterruptedException{ // 获取锁 finalReentrantLocklock=this.lock; lock.lockInterruptibly(); try{ // 自旋 for(;;) { // 获取优先级队列头节点 Efirst=q.peek(); // 优先级队列为空 ...
public E take() throws InterruptedException {final ReentrantLock lock = this.lock;lock.lockInterruptibly();try {while (count == 0)notEmpty.await();return dequeue();} finally {lock.unlock();}} 三,总结 BlockingQueue也是基于这个AQS的方式实现的,主要是利用这个生产者和消费者这个模型来实现。通过这...
Thread.sleep(200);//尝试取出元素,如果队列已空,则线程被阻塞bq.take(); }catch(InterruptedException e) { e.printStackTrace(); } System.out.println(getName()+ "消费完成:" +bq); } } }/*** @ClassName: BlockingQueueTest2 * @Description: 测试生产者线程和消费者线程的通信 ...
takeLock.unlock(); // 真正唤醒消费者线程 } } 出队take方法 public E take() throws InterruptedException { E x; int c = -1; final AtomicInteger count = this.count; final ReentrantLock takeLock = this.takeLock; // 使用takeLock加锁 takeLock.lockInterruptibly(); try { // 如果队列无元素,...