java生产者消费者问题

小Eddy 2015-06-11 12:02:50
我写了一个生产者消费者的例子,发现一直出现只有一个线程在运行的情况,调试了一下发现是其中一个Condition的阻塞线程的await方法无效
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
*
* @author Administrator
* 生产者消费者实例
*/
public class ProducerAndCustomer {
private static Buffer buffer=new Buffer(); //内部类,用于缓冲生产的商品数

public static void main(String args[]){
ExecutorService executor=Executors.newFixedThreadPool(2);
executor.execute(new buyTask());
executor.execute(new produceTask());
executor.shutdown();
}

//执行消费者的任务
private static class buyTask implements Runnable{

@Override
public void run()
{
while(true)
{
buffer.buy((int)Math.random()*10+1);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

//执行生产者的任务
private static class produceTask implements Runnable{

@Override
public void run()
{
while(true)
{
buffer.produce((int)Math.random()*10+1);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

//内部类,用于缓冲生产的商品数
public static class Buffer{
int maxNumber=20; //缓冲区的最大容量
private static int proNumber=0; //当前缓冲区的容量,为了方便,直接用整数表示
private static Lock lock=new ReentrantLock();
private static Condition notFull=lock.newCondition();
private static Condition notEmpty=lock.newCondition();

public void produce(int amount){ //生产者的方法
lock.lock();
try{
proNumber += amount;
while(proNumber==maxNumber)
{
System.out.println("wait for the not full condition");
notFull.await(); //调试时这句使线程等待的语句不起作用
}
notEmpty.signal();
}
catch(Exception e){e.printStackTrace();}
finally
{
lock.unlock();
}
}

public void buy(int amount) //消费者的方法
{
lock.lock();
try
{
while(proNumber==0)
{
System.out.println("wait for the not Empty condition");
notEmpty.await();
}

notFull.signal();
}
catch(Exception e){e.printStackTrace();}
finally
{
lock.unlock();
}
}
}

}

这是什么原因呢???
...全文
170 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
开不了口1990 2015-06-11
  • 打赏
  • 举报
回复
你这个可以跟ArrayBlockingQueue差不多吧
小Eddy 2015-06-11
  • 打赏
  • 举报
回复
知道问题所在了,在消费者线程里少了减少商品的语句........

50,526

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧