線程的生產(chǎn)者和消費(fèi)者管程法的代碼
/*
?* 使用管程法實(shí)現(xiàn)生產(chǎn)者消費(fèi)者模式
?*/
public class CoTest01 {
?? ?public static void main(String[] args) {
?? ??? ?SynContainer container=new SynContainer();
?? ??? ?new Productor(container).start();
?? ??? ?new Consumer(container).start();
?? ?}
}
//多線程的生產(chǎn)者
class Productor extends Thread {
?? ?SynContainer container;
?? ?public Productor(SynContainer container) {
?? ??? ?this.container = container;
?? ?}
?? ?@Override
?? ?public void run() {
?? ??? ?// 生產(chǎn)
?? ??? ?for (int i = 1; i < 100; i++) {
?? ??? ??? ?System.out.println("生產(chǎn)第 -->"+i+"個饅頭");
?? ??? ??? ?container.push(new Steamedbun(i)); //new了饅頭的對象
?? ??? ?}
?? ?}
}
//多線程的消費(fèi)者
class Consumer extends Thread {
?? ?SynContainer container;
?? ?public Consumer(SynContainer container) {
?? ??? ?this.container = container;
?? ?}
?? ?@Override
?? ?public void run() {
?? ??? ?// 消費(fèi)
?? ??? ?for (int i = 0; i < 1000; i++) {
?? ??? ??? ?System.out.println("消費(fèi)第-->"+container.pop().id+"個饅頭");
?? ??? ??? ?
?? ??? ?}
?? ?}
}
//緩沖區(qū)
class SynContainer {
?? ?// 存儲數(shù)據(jù)的容器
?? ?Steamedbun[] buns = new Steamedbun[10];
?? ?int count = 0;// 計數(shù)器
?? ?// 儲存-->生產(chǎn)者做的事情
?? ?public synchronized void push(Steamedbun bun) {
?? ??? ?//何時能生產(chǎn)? 容器存在空間
?? ??? ?//不能生產(chǎn)? 只有等待
?? ??? ?if(count==buns.length) {
?? ??? ??? ?try {
?? ??? ??? ??? ?this.wait();??? //線程阻塞,消費(fèi)者通知生產(chǎn)解除
?? ??? ??? ?} catch (InterruptedException e) {
?? ??? ??? ??? ?
?? ??? ??? ??? ?e.printStackTrace();
?? ??? ??? ?}
?? ??? ?}
?? ??? ?//存在空間可以生產(chǎn)
?? ??? ?buns[count] = bun;
?? ??? ?count++;
?? ??? ?//存在數(shù)據(jù)了,可以通知消費(fèi)了
?? ??? ?this.notifyAll();
?? ?}
?? ?// 獲取-->消費(fèi)者做的事情
?? ?public synchronized Steamedbun pop() {
?? ??? ?//何時消費(fèi)??? 看容器中是否存在數(shù)據(jù)
?? ??? ?//沒有數(shù)據(jù)只有等待
?? ??? ?if(count==0) {
?? ??? ??? ?try {
?? ??? ??? ??? ?this.wait();//線程阻塞?? 生產(chǎn)者通知消費(fèi)解除阻塞
?? ??? ??? ?} catch (InterruptedException e) {
?? ??? ??? ??? ?// TODO Auto-generated catch block
?? ??? ??? ??? ?e.printStackTrace();
?? ??? ??? ?}
?? ??? ?}
?? ??? ?//存在數(shù)據(jù)可以消費(fèi)
?? ??? ?count--;
?? ??? ?Steamedbun bun = buns[count];
?? ??? ?this.notifyAll();//消費(fèi)了有空間了就可以通知你生產(chǎn)了
?? ??? ?return bun;
?? ?}
}
//饅頭
class Steamedbun {
?? ??? ?int id;
?? ??? ?public Steamedbun(int id) {
?? ??? ??? ?this.id = id;
?? ??? ?}
?? ??? ?
}
標(biāo)簽: