生产者消费者问题 Thread
前段时间又回头看了看java基础的线程问题,感觉就是不一样;
容易得多,当初第一次真的搞晕人;
顺便试了一下,多生产者消费者的同步通信问题:
由生产者,消费者,仓库 三部分组成Product的处理
贴出来,交流一下。
package package com.pdsu.zhang.thread;import java.util.LinkedList;import java.util.Queue;class Product { //产品private int ID;private String name;public Product(int id, String name) {ID = id;this.name = name;}@Overridepublic String toString() {return "["+ID+"--"+name+"]";}}class Store {//仓库private final int MAX=10;private int flag=-1;Queue<Product> list =new LinkedList<Product>();// 队列private int id=0;Product temp;synchronized void add(){if(judge()==1){System.out.println("生产者 "+Thread.currentThread().getName()+" :仓库已满,请稍后生产.....");try {this.wait();//Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}}else{temp=new Product(++id,"产品");if(judge()==-1){list.offer(temp);this.notify();}elselist.offer(temp);System.out.println(Thread.currentThread().getName()+" 生产入仓库:"+temp.toString());// 不放在run{}中,否则会:先打印消费后生产! 因为print和add没有被同步;try {// 等会儿再生产,模拟生产耗时Thread.sleep(200);} catch (InterruptedException e) {e.printStackTrace();}}}synchronized void get(){if(judge()==-1){System.out.println("消费者 "+Thread.currentThread().getName()+" :仓库无货,请稍后再来.....");try {this.wait();//Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}}else{if(judge()==1){temp = list.poll();this.notify();// 不通知就会死等,死锁了}elsetemp = list.poll();System.out.println(Thread.currentThread().getName()+" 消费了产品:"+temp.toString());// 不放在run{}中,同上:try {// 等会儿再消费,模拟消费耗时Thread.sleep(200);} catch (InterruptedException e) {e.printStackTrace();}}}// 判断仓库的库存量synchronized int judge(){if(list.size()>=MAX) flag=1;else if(list.isEmpty()) flag=-1;else flag=0;return flag;}}class Producer implements Runnable {//生产者Store s;public Producer(Store s) {this.s = s;}public void run() {while(true){s.add();}}}class Customer implements Runnable{//消费者Store s;public Customer(Store s) {this.s = s;}public void run() {while(true){s.get();}}}public class Producer_Customer {/** * @param args * @author zhangli */public static void main(String[] args) {Store s = new Store();Producer p= new Producer(s);Customer c= new Customer(s);Producer p1= new Producer(s);Customer c1= new Customer(s);Producer p2= new Producer(s);Customer c2= new Customer(s);new Thread(p,"p0").start();new Thread(c,"c0").start();new Thread(p1,"p1").start();new Thread(c1,"c1").start();new Thread(p2,"p2").start();new Thread(c2,"c2").start();}}