producerconsumerdemo.java

来自「该程序是模拟JAVA中多线程机制」· Java 代码 · 共 99 行

JAVA
99
字号
package com.david;

public class ProducerConsumerDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Box box = new Box();
      Producer p = new Producer(box);
      Consumer c = new Consumer(box);
      new Thread(p).start();
      new Thread(c).start();
	}

}
class Bread{
	private int id;
	Bread(){}
	 Bread(int id){
		 this.id = id;
	 }
	 public String toString(){
			return " "+id;
		}
}
class Box{
	private int index = 0;
	Bread[] bread = new Bread[6];
	public synchronized void put(Bread bd){
		while(index == bread.length){
		try {
				wait();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		}
		bread[index] = bd;
		index++;
		this.notify();
	}	
	public synchronized Bread get(){
		while(index == 0){
		try {
				wait();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		}
		//bread[index] = bd;
		index--;
		this.notify();
		return bread[index];
        
	}	
	
}
class Producer implements Runnable{
	Box box;
	Producer(Box box){
		this.box = box;
	}
	public void run(){
			for(int i = 0;i<20;i++){
				Bread bd = new Bread(i);
				box.put(bd);
				System.out.println("the producer is producing bread:"+bd);
				try {
					Thread.sleep((int)(Math.random()*1000));
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				
			}
		}
}
class Consumer implements Runnable{
	Box box;
	Consumer(Box box){
		this.box = box;
	}
	public void run(){
		 
			for(int i = 0;i<20;i++){
				Bread bd = box.get();
				 System.out.println("the Consumer is consuming bread:"+bd);
			try {
			Thread.sleep((int)(Math.random()*1500));
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			}
		}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?