生产者-使用信号量的消费者实现

时间:2019-06-29 06:11:32

标签: java concurrency

让我们假设以下内容:

  • 生产者P1,P2。
  • 消费者C1,C2。

C1应该将P1放入缓冲区,而C2应该将P2放入缓冲区。

如果C1或C2访问缓冲区但没有消耗的物品会发生什么?

例如,C1可以访问缓冲区,但是P1在缓冲区中没有产生任何元素,是否会导致活动锁?

1 个答案:

答案 0 :(得分:0)

想法是将ConsumerProducer设计为Thread,并使用数据结构对其进行操作,并使用synchronized进行阻塞。您应该查看Thread类以及如何使用wait-notify

class DS extends ArrayList<String>
{
   public void synchronized addItem(String item)
   {
       this.add(item);
       notify();
   }
   public String synchronized getItem()
   {
       while(this.size()==0)
       {
            try
            {
              wait();
            }
            catch (InterruptedException e) { }; 
       }
       String out = this.get(0);
       this.remove(0)
       return out;
   }
}
...
class Producer extends Thread {
DS ds;
public Producer(DS ds)
{
    this.ds = ds;
}
...
     public void run()
     { 
        while(true)
        {
              try {Thread.sleep((long) (1000*Math.random()));}
              catch (InterruptedException e){e.printStackTrace();}
              String products[] = {"A", "B" ,"C" , "D" };
              int select = (int)((products.length)*Math.random());
              ds.addItem(products[select]);
              System.out.println("add product:"+products[select]);
        }
     }
...
}
class Consumer extends Thread { ... 
//similar with Producer but this time will get a product on run()
}

class Main
{
    DS ds = new DS();
    Consumer c = new Consumer(ds);
    Producer p = new Producer(ds);
    c.start();
    p.start();
}
相关问题