我有一个A类,属性是LinkedBlockingQueue。在A的一个方法中,我调用了LinkedBlockingQueue.put()方法,因为我想在队列中插入一个项。但是,如果队列已满,我的线程将等待,直到空间可用,或者直到我的线程被中断。
问题是,即使我的线程被中断,我也希望项目在队列中。
有没有办法确保我的项目已被插入到队列中?
谢谢
发布于 2012-06-13 23:58:28
我看到的唯一方法是在循环中调用queue.put()。也许是这样吧
boolean added = false;
while ( !added){
try{
queue.put(value);
added = true;
}catch(InterruptedException ie){
// do something if required
// make sure to set the interrupted flag on the thread, since it was cleared
// when the exception was thrown
Thread.currentThread().interrupt();
}
}
if(Thread.currentThread.isInterrupted()){
// you were previously interrupted before, so try to exit gracefully
return;
}发布于 2012-06-13 23:54:18
您必须决定是否要等待队列是否已满。如果您设置了最大长度,您不能告诉它忽略最大长度。
如果队列太大,你可以做的是减慢生产者的速度。如果您愿意,这将允许您“忽略”最大值。例如在中断时。
https://stackoverflow.com/questions/11018668
复制相似问题