java多线程经典的生产者消费者问题

import java.io.*;
import java.lang.*;
import java.util.*;
public class hehe {
	public static void main(String[] args){
		Stack1 s= new Stack1();
		Pruducer p= new Pruducer(s);
		Consumer c = new Consumer(s);
		new Thread(p).start();
		new Thread(c).start();
	}
}

public class Stack1 {
	Wutou[] arr = new Wutou[6];
	int index = 0;
	public synchronized void push  (Wutou wt){
		while(index == arr.length){//不用if的原因是可能异常会打断
			try{
				this.wait();//当前的对象访问的线程wait
			}catch(InterruptedException e){
				e.printStackTrace(); ;
			}
		}
		this.notifyAll();
		arr[index++] = wt;
	}
	
	public synchronized Wutou pop(){
		while(index == 0){
			try{
				this.wait();//当前的对象访问的线程wait
			}catch(InterruptedException ee){
				ee.printStackTrace();
			}
		}
		this.notifyAll();//叫醒一个线程继续执行
		return arr[--index];
	}
	
}


public class Wutou{
	int id;
	public Wutou(int id1){
		id = id1;
	}
	public String toString(){
		return "Wutou:"+ id;
	}
}


public class Pruducer implements Runnable {
	Stack1 ss = null;
	Pruducer (Stack1 ss){
		this.ss = ss;
	}
	public void run(){
		for(int i = 0;i < 20;++ i){
			Wutou w = new Wutou(i);
			ss.push(w);
			System.out.println("生产了:"+w);
			try {
				Thread.sleep(2000);
			}catch(InterruptedException e){
				return ;
			}
		}
	}
}



public class Consumer implements Runnable{
	Stack1 ss =null;
	Consumer(Stack1 ss){
		this.ss =ss ;
	}
	public void run(){
		for(int i = 0;i < 20;++ i ){
			Wutou w = new Wutou(i);
			ss.pop();
			System.out.println("消费了:"+w);
			try {
				Thread.sleep(2000);
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值