多线程模拟producer和consumer问题
package com.dijkstra;
public class Buffer {
private int contents;//
private boolean avaliable = false;
public synchronized int get() {
while (!avaliable) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int value = contents;
avaliable = false;
System.out.println("取出:\t" + contents);
this.notifyAll();
return value;
}
public synchronized void put(int value) {
while (avaliable) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
contents = value;
avaliable = true;
System.out.println("存入\t" + contents);
this.notifyAll();
}
}
=======================================================
package com.dijkstra;
public class Producer extends Thread {
private Buffer buf;
private String name;
public Producer(Buffer buf, String name) {
super();
this.buf = buf;
this.name = name;
}
public void run() {
for (int i = 0;;) {
buf.put(i);
System.out.println("生产者" + name + "生产" + i++);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
===================================================
package com.dijkstra;
public class Consumer extends Thread {
private Buffer buf;
private int number;
public Consumer(Buffer buf, int number) {
// super();
this.buf = buf;
this.number = number;
}
public void run() {
for (;;) {
//
int v = buf.get();
System.out.println("消费者" + number + "消费" + v);
}
}
}
===============================================================
package com.dijkstra;
public class ProducerConsumerProblem {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Buffer buf = new Buffer();
new Producer(buf, "\tprducer1\t").start();
new Consumer(buf, 1).start();
new Consumer(buf, 2).start();
new Consumer(buf, 3).start();
}
}
=================================================
运行结果:
存入 0
生产者 prducer1 生产0
取出: 0
消费者2消费0
存入 1
生产者 prducer1 生产1
取出: 1
消费者3消费1
存入 2
生产者 prducer1 生产2
取出: 2
消费者1消费2
存入 3
生产者 prducer1 生产3
取出: 3
消费者1消费3
存入 4
取出: 4
消费者2消费4
生产者 prducer1 生产4
存入 5
生产者 prducer1 生产5
取出: 5
消费者2消费5....................