我用下面的阻塞队列替换了以下代码。
为什么我会收到队列已满异常 - 阻塞队列不是应该阻止这种情况发生吗?
class Offer implements Runnable{
Random r=new Random();
public void run(){
while(System.currentTimeMillis() < end){
synchronized(b){
try{
while(b.size()>10){
b.wait();
}
b.add(r.nextInt());
b.notify();
}catch(InterruptedException x){}
}
}
}
}
class Take implements Runnable{
public void run(){
while(System.currentTimeMillis() < end){
synchronized(b){
try{
while(b.size()<1){
b.wait();
}
b.remove(0);
b.notify();
}catch(InterruptedException x){}
}
}
}
}
阻塞队列等效 -
BlockingQueue<Integer> b = new ArrayBlockingQueue<Integer>(10);
class Offer implements Runnable{
Random r=new Random();
public void run(){
while(System.currentTimeMillis() < end){
b.add(r.nextInt());
}
}
}
class Take implements Runnable{
public void run(){
while(System.currentTimeMillis() < end){
b.remove(0);
}
}
}
最佳答案
由于 wait()
和 notify()
是阻塞操作,因此您应该使用 BlockingQueue
中的阻塞操作:put()
和 take()
。作为一般建议:永远不要吞下 InterruptedException
。 Here是一篇关于处理 InterruptedException 的好文章。
因此,您的 BlockingQueue
替换为 synchronized
应如下所示:
BlockingQueue<Integer> b = new ArrayBlockingQueue<Integer>(10);
class Offer implements Runnable{
Random r=new Random();
public void run(){
while(System.currentTimeMillis() < end){
try {
b.put(r.nextInt());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
class Take implements Runnable{
public void run(){
while(System.currentTimeMillis() < end){
try {
b.take();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
关于java - 阻塞队列替代synchronized,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43956250/