首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

一个简略的生产者/消费者例子

2013-01-26 
一个简单的生产者/消费者例子import java.util.ArrayListimport java.util.Listclass Plate {private Li

一个简单的生产者/消费者例子

import java.util.ArrayList;import java.util.List;class Plate {private List<Object> apples = new ArrayList<Object>();public synchronized void putApple(Object apple) {if(apples.size() > 0) {try {wait();} catch (InterruptedException e) {e.printStackTrace();}}apples.add(apple);notify();System.out.println("放入了一个苹果");}public synchronized void getApple() {if(apples.size() == 0) {try {wait();} catch (InterruptedException e) {e.printStackTrace();}}Object apple = apples.get(0);apples.clear();notify();System.out.println("拿到一个苹果");}}class Add implements Runnable {private Plate applePlate;private Object apple = new Object();public Add(Plate applePlate) {this.applePlate = applePlate;}@Overridepublic void run() {for(int i=0; i<5;i++) {applePlate.putApple(apple);}}}class Get implements Runnable {private Plate applePlate;public Get(Plate applePlate) {this.applePlate = applePlate;}@Overridepublic void run() {for(int i=0; i<5;i++) {applePlate.getApple();}}}public class SynchroTest {public static void main(String args[]) {Plate myPlate = new Plate();new Thread(new Get(myPlate)).start();new Thread(new Add(myPlate)).start();}}


热点排行