Java 阻塞队列以替换已同步
我用下面的阻塞队列替换了以下代码。Java 阻塞队列以替换已同步,java,Java,我用下面的阻塞队列替换了以下代码。 为什么我会得到一个队列完全异常-阻塞队列不应该阻止这一点吗 class Offer implements Runnable{ Random r=new Random(); public void run(){ while(System.currentTimeMillis() < end){ synchronized(b){
为什么我会得到一个队列完全异常-阻塞队列不应该阻止这一点吗
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){}
}
}
}
}
类提供实现可运行{
随机r=新随机();
公开募捐{
while(System.currentTimeMillis()10){
b、 等待();
}
b、 添加(r.nextInt());
b、 通知();
}捕获(中断异常x){}
}
}
}
}
类Take实现可运行{
公开募捐{
while(System.currentTimeMillis()wait()
和notify()
是阻塞操作时,您应该使用BlockingQueue
中的阻塞操作:put()
和take()
。作为一般建议:永远不要吞咽中断异常
。这是一篇关于处理中断异常
的好文章
因此,您的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();
}
}
}
}
BlockingQueue b=newarrayblockingqueue(10);
类提供实现可运行{
随机r=新随机();
公开募捐{
while(System.currentTimeMillis()
由于wait()
和notify()
是阻塞操作,您应该使用BlockingQueue
中的阻塞操作:put()
和take())
。作为一般建议:永远不要吞咽中断异常
。这是一篇关于处理中断异常
的好文章
因此,您的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();
}
}
}
}
BlockingQueue b=newarrayblockingqueue(10);
类提供实现可运行{
随机r=新随机();
公开募捐{
while(System.currentTimeMillis()
您的消费速度不够快,因此队列已满。您需要使用put
而不是add
。简而言之,RTFM.FTFM:“add
:如果可以在不违反容量限制的情况下立即将指定元素插入此队列,则在成功时返回true,如果当前没有可用空间,则抛出非法状态异常。使用容量限制队列时,通常最好使用offer。”。"sayput
和take
块。方法add
和remove
具有不同的语义,add
抛出异常,remove
返回true
/false
表示成功。RTFM@DaveNewton复制等待
/通知
bl需要使用锁定操作。@BoristheSpider是的,我知道-我引用了OP使用的方法中的文档,因为它显示了OP看到的行为,并提供了原因。您的消费速度不够快,因此队列正在填充。您需要使用put
而不是add
。简而言之,RTFM.FTFM:“add
:如果可以在不违反容量限制的情况下立即将指定元素插入此队列,则在成功时返回true,如果当前没有可用空间,则抛出非法状态异常。使用容量限制队列时,通常最好使用offer。”。"sayput
和take
块。方法add
和remove
具有不同的语义,add
抛出异常,remove
返回true
/false
表示成功。RTFM@DaveNewton复制等待
/通知
bl需要使用锁定操作。@BoristheSpider是的,我知道-我引用了OP使用的方法中的文档,因为它显示了他们看到的行为,并提供了原因。