生产者与消费者

public class ProducerConsumer2{
    public static void main(String[] args){
        SyncStack ss = new SyncStack();
        Producer p = new Producer(ss);
        Consumer c = new Consumer(ss);
        new Thread(p).start();
        new Thread(c).start();
    }
}
class ManTou{
    int id;
    ManTou(int id){
        this.id = id;
    }
    public String toString(){
        return "ManTou" + this.id;
    }
}
class SyncStack{
    ManTou[] m = new ManTou[6];
    int index = 0;
    public synchronized void push(ManTou mt){
        while(index == m.length){
            try{
                this.wait();
            }catch(InterruptedException ie) {}
        }
        m[index] = mt;
        index ++;
        this.notifyAll();
    }
    
    public synchronized ManTou pop(){
        while(index == 0){
            try{
                this.wait();
            }catch(InterruptedException ie) {}
        }
        
        index --;
        this.notifyAll();
        return m[index];
    }
}
class Producer implements Runnable{
    SyncStack ss = null;
    Producer(SyncStack ss){
        this.ss = ss;
    }
    public void run(){
        for(int i=0;i<6;i++){
        ManTou m = new ManTou(i);
            ss.push(m);
            System.out.println("Producer" + m); 
            try { 
                Thread.sleep((int)(Math.random() * 200)); 
            } catch (InterruptedException e) { 
                e.printStackTrace(); 
            }            
        }
    }
}

class Consumer implements Runnable{
    SyncStack ss = null;
    Consumer(SyncStack ss){
        this.ss = ss;
    }
    public void run(){
        for(int i=0;i<6;i++){
            System.out.println("Consumer" + ss.pop()); 
            try { 
                Thread.sleep((int)(Math.random() * 500)); 
            } catch (InterruptedException e) { 
                e.printStackTrace(); 
            }            
        }
    }
}



弄不明白这两个程序有什么区别,上面的可以实现,但下面这个就不能了

public class ProducerConsumer2{
    public static void main(String[] args){
    //    SyncStack ss = new SyncStack();
          ManTou[] m = new ManTou[6];
          int i = 0;
        Producer p = new Producer(m,i);
        Consumer c = new Consumer(m,i);
        new Thread(p).start();
        new Thread(c).start();
    }
}
class ManTou{
    int id;
    ManTou(int id){
        this.id = id;
    }
    public String toString(){
        return "ManTou" + this.id;
    }
}
/*class SyncStack{
    ManTou[] m = new ManTou[6];
    int index = 0;
    public synchronized void push(ManTou mt){
        while(index == m.length){
            try{
                this.wait();
            }catch(InterruptedException ie) {}
        }
        m[index] = mt;
        index ++;
        this.notifyAll();
    }
    
    public synchronized ManTou pop(){
        while(index == 0){
            try{
                this.wait();
            }catch(InterruptedException ie) {}
        }
        
        index --;
        this.notifyAll();
        return m[index];
    }
}*/
class Producer implements Runnable{
        ManTou[] m = new ManTou[6];
        int index;
        Producer(ManTou[] mm,int i){
            this.m = mm;
            this.index = i;
        }
    public synchronized void run(){
        for(int i=0;i<6;i++){
        ManTou mt = new ManTou(i);
            while(index == m.length){
            try{
                this.wait();
            }catch(InterruptedException ie) {}
        }
        this.m[index] = mt;
        index ++;
        this.notifyAll();
            System.out.println("Producer" + mt);
            try {
                Thread.sleep((int)(Math.random() * 200));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }            
        }
    }
}

class Consumer implements Runnable{
ManTou[] m = new ManTou[6];
int index;
        Consumer(ManTou[] mm,int i){
            this.m = mm;
            this.index = i;
        }
    public synchronized  void run(){
        for(int i=0;i<6;i++){
                while(index == 0){
            try{
                this.wait();
            }catch(InterruptedException ie) {}
        }
        
        index --;
        this.notifyAll();
            System.out.println("Consumer" + this.m[index]);
            try {
                Thread.sleep((int)(Math.random() * 500));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }            
        }
    }
}



java编程思想的生产者与消费者:
import java.util.concurrent.*;

class Meal {
	private final int orderNum;
	public Meal(int orderNum) {
		this.orderNum = orderNum;
	}

	public String toString() {
		return "Meal " + orderNum;
	}
}

class WaitPerson implements Runnable {
	private MyRestaurant restaurant;

	public WaitPerson(MyRestaurant restaurant) {
		this.restaurant = restaurant;
	}

	public void run() {
		try {
			while (!Thread.interrupted()) {
				synchronized (this) {
					while (restaurant.meal == null) {
						wait();
					}
					//当meal为空,waitperson这个自家的线程就要等待,直到chef生产出meal
				}
				synchronized (restaurant.chef) {
					System.out.println("Watiperson got " + restaurant.meal);
					restaurant.meal = null;
					restaurant.chef.notifyAll();
				}
				//meal不空,获取chef的锁,当chef生产完成之后,waitperson取出meal并将meal设为空,然后提醒chef开始生产
			}
		} catch (InterruptedException e) {
			System.out.println("Waitperson interrupted");
		}
	}
}

class Chef implements Runnable {
	private MyRestaurant restaurant;
	private int count = 0;
	public Chef(MyRestaurant restaurant) {
		this.restaurant = restaurant;
	}

	public void run() {
		try {
			while (!Thread.interrupted()) {
				synchronized (this) {
					while (restaurant.meal != null) {
						wait();
					}
				}
				//当meal不为空,chef就要等待自家的线程,直到meal被取走
				if (++count == 10) {
					System.out.println("Out of food, closing");
					restaurant.exec.shutdownNow();
				}
				synchronized (restaurant.waitperson) {
					System.out.println("Order up !");
					restaurant.meal = new Meal(count);
					restaurant.waitperson.notifyAll();
				}
				//跟waitperson原理类似
				TimeUnit.MILLISECONDS.sleep(100);
			}
		} catch (InterruptedException e) {
			System.out.println("Chef interrupted");
		}
	}
}

public class MyRestaurant {
	Meal meal;
	ExecutorService exec = Executors.newCachedThreadPool();
	WaitPerson waitperson = new WaitPerson(this);
	Chef chef = new Chef(this);
	public MyRestaurant() {
		exec.execute(chef);
		exec.execute(waitperson);
	}

	public static void main(String[] args) {
		new MyRestaurant();			//目前只知道通过这种方法来调用execute();
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值