您的位置:首页 > 其它

生产者消费者实例

2011-01-13 01:41 148 查看
package com.thread.test;

public class ProductorConsumer {

public static void main(String[] args) {

WoTouPool pool = new WoTouPool();

Productor p1 = new Productor("p1", pool);

Productor p2 = new Productor("p2", pool);

Productor p3 = new Productor("p3", pool);

Consumer c1 = new Consumer("c1", pool);

Consumer c2 = new Consumer("c2", pool);

Consumer c3 = new Consumer("c3", pool);

new Thread(p1).start();

new Thread(p2).start();

new Thread(p3).start();

new Thread(c1).start();

new Thread(c2).start();

new Thread(c3).start();

}

}

class WoTouPool {

private int index = 0;

private WoTou[] woTous = new WoTou[10];

private Object obj = new Object();

public synchronized void pushWoTou(WoTou woTou) {

while (index == woTous.length) {

try {

obj.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

obj.notify();

woTous[index] = woTou;

index++;

System.out

.println(" 当前WoTou个数:"

+ index);

}

public synchronized WoTou popWoTou() {

while (index == 0) {

try {

obj.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

obj.notify();

index--;

System.out

.println(" 当前WoTou个数:"

+ index);

return woTous[index];

}

}

class WoTou {

private String name;

public WoTou(String name) {

this.name = name;

}

public String getName() {

return name;

}

}

class Productor implements Runnable {

private String name;

private WoTouPool woTouPool;

public Productor(String name, WoTouPool woTouPool) {

this.name = name;

this.woTouPool = woTouPool;

}

public void run() {

for (int i = 0; i < 20; i++) {

WoTou woTou = new WoTou(name + " 生产的第 " + (i + 1) + " 个产品");

woTouPool.pushWoTou(woTou);

System.out.println(woTou.getName());

try {

Thread.sleep(1);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

class Consumer implements Runnable {

private String name;

private WoTouPool woTouPool;

public Consumer(String name, WoTouPool woTouPool) {

this.name = name;

this.woTouPool = woTouPool;

}

public void run() {

for (int i = 0; i < 20; i++) {

WoTou woTou = woTouPool.popWoTou();

System.out.println(name + " 第 " + (i + 1) + " 次消费的产品,该产品的信息:"

+ woTou.getName());

try {

Thread.sleep(10);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

class TestStatic {

private static Object obj = new Object();

public synchronized static void f() {

System.out.println("---f-----");

}

public static void g() {

synchronized (obj) {

System.out.println("---g-----");

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: