问题 :
生产者 需要生产 6个产品后, 消费者 才能消费, 当消费 者 消费 一个后 生产者 继续生产.
同时进行
面向 对象:
生产者 消费者 产品 共享资源
消费者
public class Consumer implements Runnable {
Util util;
public Consumer(Util util) {
this.util=util;
new Thread(this).start();
}
public void run() {
while(true)
{
util.get();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
生产者
public class Producer implements Runnable {
Util util;
// 生产者
public Producer(Util util) {
this.util = util;
new Thread(this).start();
}
public void run() {
int i = 0;
while (true) {
Motorcycle p = new Motorcycle("川崎", i++);
util.put(p);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
生产的 产品
public class Motorcycle {
private String name;// 产品名称
int id;// 产品编号
public Motorcycle(String name, int id) {
this.name = name;
this.id = id;
}
共享资源 类
public class Util {
private Motorcycle[] boxs = new Motorcycle[5];
private int index = -1;
/*
* 放产品到盒子
*
*/
public synchronized void put(Motorcycle m) {
// if (index == boxs.length - 1) {
if (boxs[4] != null) {
System.out.println("生产者休息");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
boxs[++index] = m;
System.out.println("生产者:" + m);
notify();
}
/*
* 盒子取产品
*/
public synchronized Motorcycle get() {
//if (index == -1)// 盒子为空
if(boxs[0] ==null)
{
System.out.println("消费者休息");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Motorcycle m = boxs[index--];
System.out.println("消费者:" + m);
notify();
return m;
}
}
Test 类
public class Test {
public static void main(String[] args) {
Util u = new Util();
new Producer(u);
new Consumer(u);
}
}