`

线程—代码模拟—生产者-消费者

阅读更多
尚学堂—马士兵-java系列网上免费视频教程

知识点:
1.Thread.sleep();
2.Runnable接口
3.Object.wait()
4.Object.notify();
5.if 和 While 的区别
6.synchronized 关键字

ProducerConsumer.java

1.其实,编译后会生成5个class文件。但只需运行 ProducerConsumer.class即可。
2.如果想在你的console中显示中文,请将.java文件的编码设为GB2312

/**
 * 【生产者与消费者】
 * 
 * 注意:
 * 1、在使用wait()时,wait()最好写在while中。不要写在if else中。
 * 2、wait()语句只能使用在synchronized语句中,用于使synchronize释放对其内部对象的锁定。
 * 3、只要使用了wait(),在while外面一定要用notify();用于通知其它线程可以执行了。
 *
 */

public class ProducerConsumer {
	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 Wotou {
	int id;
	Wotou(int id){
		this.id = id;
	}
	@Override
	public String toString(){
		return "Wotou: " + id;
	}
}

class SyncStack{
	int index = 0;
	Wotou[] arrWt = new Wotou[6];
	
	public synchronized void push(Wotou wt){
		while(index == arrWt.length){
			try{
				this.wait();
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
		this.notify();
		arrWt[index] = wt;
		index ++;
	}
	public synchronized Wotou pop(){
		while(index == 0){
			try{
				this.wait();
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
		this.notify();
		index --;
		return arrWt[index];
		
	}
}

class Producer implements Runnable{
	SyncStack ss = null;
	Producer(SyncStack ss){
		this.ss = ss;
	}
	public void run(){
		for(int i=0;i<20;i++){
			Wotou wt = new Wotou(i);
			ss.push(wt);
			System.out.println("生产了:"+ wt);
			try{
				Thread.sleep(500);
			}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<20;i++){
			Wotou wt = ss.pop();
			System.out.println("消费了:"+wt);
			try{
				Thread.sleep(500);
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
	}
}










--
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics