使用管道流实现生产消费者模式
package com.thread.cooperation;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class Demo04 {
public static void main(String[] args) {
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream();
try {
pos.connect(pis);
} catch (IOException e) {
e.printStackTrace();
}
PipeProducer p = new PipeProducer(pos,"xixi");
pipeConsumer c1 = new pipeConsumer(pis, "lili");
pipeConsumer c2 = new pipeConsumer(pis, "gaogao");
p.start();
c1.start();
c2.start();
}
}
class PipeProducer extends Thread{
private PipedOutputStream pos;
public PipeProducer(PipedOutputStream pos,String name) {
super(name);
this.pos = pos;
}
@Override
public void run() {
int i = 0;
try {
while (true) {
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName()+"product:"+i);
pos.write(i);
i++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class pipeConsumer extends Thread{
private PipedInputStream pis;
public pipeConsumer(PipedInputStream pis,String name) {
super(name);
this.pis = pis;
}
@Override
public void run() {
try {
while (true) {
System.out.println(Thread.currentThread().getName()+"consumer:"+pis.read());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}