java多线程模拟生产者消费者问题
//java多线程模拟生产者消费者问题//ProducerConsumer是主类,Producer生产者,Consumer消费者,Product产品//Storage仓库public class ProducerConsumer {public static void main(String[] args) {Storage s = new Storage();Producer p = new Producer(s);Consumer c = new Consumer(s);Thread tp = new Thread(p);Thread tc = new Thread(c);tp.start();tc.start();}}class Consumer implements Runnable {//消费者 Storage s = null;public Consumer(Storage s){this.s = s;}public void run() {for(int i=0; i<20; i++){Product p = s.pop();//取出产品try {Thread.sleep((int)(Math.random()*1500));} catch (InterruptedException e) {e.printStackTrace();}}}}class Producer implements Runnable {//生产者Storage s = null;public Producer(Storage s){this.s = s;}public void run() {for(int i=0; i<20; i++){Product p = new Product(i);s.push(p); //放入产品// System.out.println("生产者放入:" + p);try {Thread.sleep((int)(Math.random()*1500));} catch (InterruptedException e) {e.printStackTrace();}}}}class Product {int id;public Product(int id){this.id = id;}public String toString(){//重写toString方法return "产品:"+this.id;}}class Storage {int index = 0;Product[] products = new Product;public synchronized void push(Product p){//放入while(index==this.products.length){try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}this.products = p;System.out.println("生产者放入"+index+"位置:" + p);index++;this.notifyAll();}public synchronized Product pop(){//取出while(this.index==0){try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}index--;this.notifyAll();System.out.println("消费者从"+ index+ "位置取出:" + this.products);return this.products;}}求实,求真相!!! 学习学习 学学一下,加油
学习学习 顶下,很简洁的例子
页:
[1]