有一个生产者消费者实例,修改了一下,觉得还行,javaeye上有类似的代码。
Producer.java
Consumer.java
Warehouse.java
Main.java
Producer.java
package com.java.lang.thread.produce_consume;
import java.util.Random;
public class Producer extends Thread {
private Warehouse warehousec;
public Producer(Warehouse warehouse) {
this.warehousec = warehouse;
}
public void run() {
Random random = new Random();
int num = 0;
for (;;) {
try {
Thread.sleep(500); // 生产速度
num = 1 + random.nextInt(10);
warehousec.put(num);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Consumer.java
package com.java.lang.thread.produce_consume;
import java.util.Random;
public class Consumer extends Thread {
private Warehouse warehouse;
public Consumer(Warehouse warehouse) {
this.warehouse = warehouse;
}
public void run() {
Random random = new Random();
int num = 0;
for (;;) {
try {
Thread.sleep(300); // 销售速度
num = 1 + random.nextInt(10);
warehouse.get(num);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Warehouse.java
package com.java.lang.thread.produce_consume;
public class Warehouse {
public int pnum = 0;
public Warehouse() {
this.pnum = 0;
}
public Warehouse(int num) {
this.pnum = num;
}
public synchronized void put(int value) throws InterruptedException {
pnum += value;
System.out.println("生产了" + value + "件产品.当前库存:" + pnum);
if(pnum >= 20){
this.notify();
}
}
public synchronized void get(int value) throws InterruptedException {
if (pnum == 0) {
System.out.println("没有货了,停止销售。");
this.wait();
}else{
if(value > pnum){
value = pnum;
}
pnum -= value;
System.out.println("销售了"+value+"件产品.当前库存:" + pnum);
}
}
}
Main.java
package com.java.lang.thread.produce_consume;
/**
* wait/notify 机制是为了避免轮询带来的性能损失。
* @author yuahan
*/
public class Main {
public static void main(String[] args) {
Warehouse warehouse= new Warehouse(10);
Producer p=new Producer(warehouse);
p.setName("生产");
Consumer consumer=new Consumer(warehouse);
consumer.setName("销售");
p.start();
consumer.start();
}
}