?ùì???3ì£oéú2ú??ó???·???
ê±??:2011-10-07 blogjava Liver
3??°?èê?£o
ò???2??a£?éú2ú???ú1¤3§à?éú2úá?2ú?·oó£???2ú?·′?·?μ?2??aà?£?2??a′?·?êyá?óD?T£?μ±?ú2?oó£?í£ ?1éú2ú£??±μ?óD??·?×???2ú?·??·?oó2??ìD?éú2ú£???·???′ó2??aà?ìáè?2ú?·£?μ±2??a??2?ê±£?í£?1??·?2ú ?·£??±μ?2??a?DóD2ú?·ê±£?2??ìD???·?2ú?·?£
′ú??μ?êμ??£¨μ÷????3ìsleepê±???éò?êμ??éú2ú?ù?èó???·??ù?èμ?2?í?£?£o
TestProduceAndConsumer.java
package com.nantian;
import java.util.Random;
public class TestProduceAndConsumer {
?????? public static void main(String[] args) {
?????????????? // ′′?¨ò???1¤3§???ó
?????????????? ProductFactory pf = new ProductFactory();
?????????????? // ′′?¨ò???éú2ú??oíò?????·???£?′?μY1¤3§μ?òyó?£?±£?¤á???2ù×÷μ?ê?í?ò???1¤3§
?????????????? Producer p = new Producer(pf);
?????????????? Consumer c = new Consumer(pf);
?????????????? // ???ˉá?????3ì
?????????????? p.start();
?????????????? c.start();
?????? }
}
// 2ú?·1¤3§
class ProductFactory {
?????? // product±íê?2??a
?????? private char[] product = { '' '', '' '', '' '', '' '', '' ''};
?????? // flag±ê??2ú?·êyá?
?????? private int flag = 0;
?????? // éú2ú2ú?·
?????? public synchronized void produceProduct(char p) throws InterruptedException {
?????????????? // ?D??2ú?·ê?·??ú2?£?ò?±????¨ê?·??ìD?éú2ú
?????????????? if (flag == product.length) {
?????????????????????? this.wait();
?????????????? }
?????????????? // μ±′ú???′DDμ??aà?£?ò??¨2?ê??ú2?×′ì?
?????????????? product[flag++] = p;
?????????????? // 2é?′′?ê±2??a×′ì?£¨?aà?2?ê?óúòμ?????-2?·?£?
?????????????? System.out.print(p + "±?éú2ú£?μ±?°2??a×′ì?£o");
?????????????? for (char tmp : product) {
?????????????????????? System.out.print(tmp);
?????????????? }
?????????????? System.out.println();
?????????????? // éú2ú·?·¨íê3é£?è?1?′??úμè′y?óáD?Dμ???3ì£?ó|????D?
?????????????? this.notifyAll();
?????? }
?????? // ??·?2ú?·
?????? public synchronized char consumeProduct() throws InterruptedException {
?????????????? // ?D??2??aê?·???2?£?ò?±????¨ê?·???·?2ú?·
?????????????? if(flag == 0) {
?????????????????????? this.wait();
?????????????? }
?????????????? // μ±′ú???′DDμ??aà?£?ò??¨2?ê???2?×′ì?
?????????????? char p = product[--flag]; product[flag]='' '';
?????????????? // 2é?′′?ê±2??a×′ì?£¨?aà?2?ê?óúòμ?????-2?·?£?
?????????????? System.out.print(p + "±???·?£?μ±?°2??a×′ì?£o");
?????????????? for(char tmp : product) {
?????????????????????? System.out.print(tmp);
?????????????? }
?????????????? System.out.println();
?????????????? // ??·?·?·¨íê3é£?è?1?′??úμè′y?óáD?Dμ???3ì£?ó|????D?
?????????????? this.notifyAll();
?????????????? return p;
?????? }
}
// éú2ú??
class Producer extends Thread {
?????? private P
|