本帖最后由 as604049322 于 2014-12-25 17:38 编辑
看完毕老师的多线程视频,自己写的第三个源码。
运行效果截图:
- /*
- 需求分析:有一群生产者和一群消费者,
- 生产的商品都由一个对象来保存,生产者生产时,消费者不得进行购买动作,生产完成后才可以进行购买
- 同样消费者购买商品时生产者不得生产。
- */
- class ProducerConsumer
- {
- public static void main(String[] args)
- {
- Resource r=new Resource();
- Producer p=new Producer(r);
- Consumer c=new Consumer(r);
- new Thread(p,"生产者1").start();
- new Thread(p,"生产者2").start();
- new Thread(p,"生产者3").start();
- new Thread(c,"消费者1").start();
- new Thread(c,"消费者2").start();
- new Thread(c,"消费者3").start();
- new Thread(c,"消费者4").start();
- new Thread(c,"消费者5").start();
- }
- }
- class Resource
- {
- String name;
- int count;
- boolean flag=false;
- public synchronized void produce(String name){
- while(flag)
- try{wait();}catch(Exception e){}
- this.name=name;
- System.out.println(Thread.currentThread().getName()+":生产一个商品,信息如下:");
- System.out.println("产品名称:"+name+",产品编号:"+(++count));
- System.out.println("-----------------------------------------------------");
- flag=true;
- notifyAll();
- }
- public synchronized void consume(){
- while(!flag)
- try{wait();}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+":某个商品被购买,信息如下:");
- System.out.println("产品名称:"+name+",产品编号为:"+count);
- System.out.println("-----------------------------------------------------");
- flag=false;
- notifyAll();
- }
- }
- class Producer implements Runnable
- {
- private final Resource r;
- Producer(Resource r){
- this.r=r;
- }
- public void run(){
- while(true)
- r.produce(creatRandomName());
- }
- public static String creatRandomName(){
- String[] name={"加饭酒","茅台酒","21金维他","两面针","牙膏","电视机","计算机","桌子","衣服"};
- return name[(int)(Math.random()*name.length)];
- }
- }
- class Consumer implements Runnable
- {
- private final Resource r;
- Consumer(Resource r){
- this.r=r;
- }
- public void run(){
- while(true)
- r.consume();
- }
- }
复制代码
|