import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static net.mindview.util.Print.*;
/**
* 生产者-消费者问题的变体
* 通过输入/输出在线程间进行通信
* 这里的管道是一个封装好的解决方案
* 管道基本上是一个阻塞队列
*
* @author cxp
* @data 2016-09-01
* @modify
*
*/
// 发送者
class Sender implements Runnable {
private Random rand = new Random(47);
private PipedWriter out = new PipedWriter();//允许任务向管道写
public PipedWriter getPipedWriter() {
return out;
};
public void run() {
try {
while (true)
for (char c = 'A'; c <= 'z'; c++) {
out.write(c);
TimeUnit.MILLISECONDS.sleep(rand.nextInt(500));
}
} catch (IOException e) {
print(e + " Sender writer exception");
} catch (InterruptedException e) {
print(e + " Sender sleep interrupted");
}
}
}
// 接收者
class Receiver implements Runnable {
private PipedReader in;//允许不同任务从同一管道中读取
public Receiver(Sender sender) throws IOException {
in = new PipedReader(sender.getPipedWriter());
}
public void run() {
try {
while (true) {
// 阻塞直到字符到达这里
print("Read: " + (char) in.read() + ", ");
}
} catch (IOException e) {
print(e + " Receiver read exception");
}
}
}
public class PipedIO {
public static void main(String[] args) throws Exception {
Sender sender = new Sender();
Receiver receiver = new Receiver(sender);
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(sender);
exec.execute(receiver);
TimeUnit.SECONDS.sleep(4);
exec.shutdownNow();
}
}
生产者-消费者问题与管道
最新推荐文章于 2022-02-24 09:41:19 发布