2.一個具體的產品類:
public class AProduct extends Product {
public AProduct(String name) {
this.name = name;
// TODO Auto-generated constructor stub
}
public String toString() {
// TODO Auto-generated method stub
return this.name;
}
}
3.容器類(倉庫):
import java.util.ArrayList;
/*
* 存放生產者和消費者的產品隊列
* */
public class Container {
private ArrayList arrList = new ArrayList();
private int LENGTH = 10;
public boolean isFull() {
return arrList.size()==LENGTH;
}
public boolean isEmpty() {
return arrList.isEmpty();
}
/* 如果此處不加synchronized鎖,那么也可以再調用push的地方加鎖
* 既然此處加了鎖,那么再別的地方可以不加鎖
*/
public synchronized void push(Object o) {
arrList.add(o);
}
// 如果此處不加synchronized鎖,那么也可以再調用push的地方加鎖
public synchronized Object pop() {
Object lastOne = arrList.get(arrList.size()- 1);
arrList.remove(arrList.size()- 1);
return lastOne;
}
}
4.休息一會,生產者和消費者都要休息,因此作為抽象基類:
public abstract class Sleep {
public void haveASleep() throws InterruptedException {
Thread.sleep((long)(Math.random()* 3000));
}
}
/*
* 消費者線程
* */
public class Consumer extends Sleep implements Runnable {
private Container contain =null;
public Consumer(Container contain) {
this.contain = contain;
}
public void run() {
// TODO Auto-generated method stub
while(true) {
synchronized(contain) {
while(contain.isEmpty()) {
try{
contain.wait();
}catch(InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
consume();//消費
try {
haveASleep();
}catch(InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(contain) {
contain.notify();
}
}
}
private void consume() {
Product a = (AProduct)contain.pop();
System.out.println("消費了一個產品"+ a.toString());
}
}
/*
* 生產者線程
* */
public class Producator extends Sleep implements Runnable {
private Container contain = null;
public Producator(Container contain) {
super();
this.contain = contain;
}
public void run() {
// TODO Auto-generated method stub
while(true) {
synchronized(contain) {
while(contain.isFull()) {
try{
contain.wait();// 阻塞當前線程,當前線程進入等待隊列。這個時候只有等待別的線程來喚醒自己了。
}catch(InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
producer();// 生產一個產品
try {
haveASleep();
}catch(InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(contain) {
contain.notify();// 喚醒等待隊列中正在等待的第一個線程,讓其執行。
}
}
}
public void producer() {
Product aProduct = new AProduct("pp:"+String.valueOf((int)(10*Math.random())));
System.out.println("生產了一個產品:"+ aProduct.toString());
contain.push(aProduct);
}
}
5. 寫一個測試:
public class TestMain {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Container contain = new Container();
Producator p = new Producator(contain);
Consumer c = new Consumer(contain);
Thread pt =new Thread(p);
Thread ct =new Thread(c);
pt.start();
ct.start();
}
}