整理工程時發現之前敲的關於生產者消費者問題的代碼,發現寫的邏輯太混亂了,在網上搜了下資料以後重新寫了一遍。
基本思路是這樣的,一個盤子裏有若干個雞蛋雞蛋,生產者往盤子裏放雞蛋,消費者取雞蛋,當盤子滿時生產者不能再放雞蛋,盤子空時不能再取雞蛋。在這裏用LinkedList實現棧,作爲存放固定個數雞蛋的盤子。
雞蛋代碼:
package testfile;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.io.*;
/** 定義一個盤子類,可以放雞蛋和取雞蛋 */
public class testThread {
/** 裝雞蛋的盤子 */
int max_size=10;
LinkedList<Object> eggs = new LinkedList<Object>();
/** 取雞蛋 */
public synchronized Object getEgg() {
while (eggs.size() == 0) {
try {
System.out.println("get action wait");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Object egg = eggs.getFirst();
System.out.println("get an egg");
eggs.removeFirst();
notifyAll();
return egg;
}
/** 放雞蛋 */
public synchronized void putEgg(Object egg) {
while (eggs.size() > 9) {
try {
System.out.println("put action wait");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
eggs.add(egg);// 往盤子裏放雞蛋
System.out.println("put an egg");
notifyAll();// 喚醒阻塞隊列的某線程到就緒隊列
}
static class AddThread implements Runnable {
private testsynchronic plate;
private Object egg = new Object();
public AddThread(testsynchronic plate) {
this.plate = plate;
}
public void run() {
plate.putEgg(egg);
}
}
static class GetThread implements Runnable {
private testsynchronic plate;
public GetThread(testsynchronic plate) {
this.plate = plate;
}
public void run() {
plate.getEgg();
}
}
public static void main(String args[]) {
testThread plate = new testThread();
Thread t1= new Thread(new AddThread(plate));
Thread t2= new Thread(new AddThread(plate));
Thread t3= new Thread(new AddThread(plate));
Thread t4= new Thread(new GetThread(plate));
Thread t5= new Thread(new GetThread(plate));
Thread t6=new Thread(new GetThread(plate));
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
}
}
還有用線程池實現的生產者消費者問題,http://www.cnblogs.com/linjiqin/p/3217050.html