fib*_*era 2 java multithreading blockingqueue
在下面的伪代码中,我有一个poll()在主线程中永远调用的函数.如果我在没有sleep()声明的情况下执行此操作,则poll()每分钟只有2-3个项目被另一个线程添加到队列中.这是否意味着轮询会阻止该put()声明?
我怎么解决这个问题?
public class Test extends Thread{
private LinkedBlockingQueue<Object> queue = null;
Test(){
queue = new LinkedBlockingQueue<Object>(10);
}
public void run(){
// Do stuff, get incoming object from network
queue.put(o);
}
public Object poll(){
Object o = queue.poll();
sleep(1000);
return o;
}
}
Run Code Online (Sandbox Code Playgroud)
Gra*_*ray 13
这是否意味着轮询会阻止put()语句?
不,LinkedBlockingQueue是完全可重入的,并且该poll()方法不会阻止put().但是,该poll()方法立即返回.您可能应该使用queue.take()等待队列中的项目而不是在队列为空时返回null.
// wait for there to be an object in the queue
Object o = queue.take();
// no sleep necessary
return o;
Run Code Online (Sandbox Code Playgroud)
由于您正在构建一个包含10个条目的约束阻塞队列,我猜主要是阻塞,sleep()然后队列填满并减慢您的程序.你也许应该只sleep,如果有poll()返回null和睡眠的时间更短的量.
编辑:作为注释中提到的@JohnVint,另一种方法是使用poll(long, TimeUnit)等待项目在该时间段内添加到队列中的方法,并null在计时器到期时返回.这是一种等待队列中某些东西的更简洁方法.
// wait for 1000ms for there to be an object in the queue
Object o = queue.poll(1000, TimeUnit.MILLISECONDS);
// no sleep necessary
return o;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9295 次 |
| 最近记录: |