- package day26;
- /**超过两个线程的
- * 生产者消费者模式*/
- public class ProducerAndCustomerTest {
- public static void main(String args[]) {
- Resource4 rs = new Resource4();
- Producer producer = new Producer(rs);
- Customer customer = new Customer(rs);
- Thread thread1 = new Thread(producer);
- Thread thread2 = new Thread(producer);
- Thread thread3 = new Thread(customer);
- Thread thread4 = new Thread(customer);
- thread1.start();
- thread2.start();
- thread3.start();
- thread4.start();
- }
- }
- class Resource4{
- private String name;
- private int count=1 ;
- private boolean flag = false;
- // t1 t2
- public synchronized void set(String name){
- while(flag){
- try{this.wait();}catch(Exception e){}//t1(放弃资格) t2(获取资格)
- }
- // if(flag){
- // System.out.println("生产者应该挂起");
- // try{this.wait();}catch(Exception e){}
- // }
- System.out.println("生产线程挂起结束");
- this.name = name+"----"+(count++);
- System.out.println(Thread.currentThread().getName()+"^^^生产者"+this.name);
- flag = true;
- this.notifyAll();
- //this.notify();
- }
- public synchronized void out(){
- while(!flag){
- try{this.wait();}catch(Exception e){}//t3(放弃资格) t4(获取资格)
- }
- // if(!flag){
- // System.out.println("消费者应该挂起");
- // try{this.wait();}catch(Exception e){}
- //
- // }
- System.out.println("消费线程挂起结束");
- System.out.println(Thread.currentThread().getName()+"^^^消费者"+this.name);
- flag = false;
- this.notifyAll();
- //this.notify();
- }
- }
- class Producer implements Runnable{
- private Resource4 rs ;
- public Producer(Resource4 rs){
- this.rs = rs;
- }
- public void run(){
- while(true){
- rs.set("商品");
- }
- }
- }
- class Customer implements Runnable{
- private Resource4 rs ;
- public Customer(Resource4 rs){
- this.rs = rs;
- }
- public void run(){
- while(true){
- rs.out();
- }
- }
- }
复制代码 为什么我的产品序号不对啊?
|