首页 > 其他 > 详细

任务间使用管道进行输入输出

时间:2015-04-23 23:30:11      阅读:281      评论:0      收藏:0      [点我收藏+]

内容:通过输入/输出在线程间进行通信通常很有用。利用PipedWriter类(允许任务向管道写)和PipedReader类(允许不同任务从同一个管道中读取)。下面代码中Sender和Receiver代表了需要相互通信的两个任务。Sender把数据放进Writer,然后休眠一段时间。然而,Receiver没有sleep()和wait()。但当他调用read()时,如果没有更多的数据,管道将阻塞,而普通I/O是不能打断的。

class Sender implements Runnable {
	private Random rand = new Random(47);
	private PipedWriter out = new PipedWriter();
	
	public PipedWriter getPipedWriter() {
		return out;
	}
	
	@Override
	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) {
			System.out.println(e + " Sender write exception");
		} catch (InterruptedException e) {
			System.out.println(e + "Sender sleeo interrupted");
		}
	}
}

class Receiver implements Runnable {
	private PipedReader in;
	
	public Receiver(Sender sender) throws IOException {
		in = new PipedReader(sender.getPipedWriter());
	}
	
	@Override
	public void run() {
		try {
			while (true) {
				System.out.println("Read: " + (char)in.read() + ". ");
			}
		} catch (IOException e) {
			System.out.println(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();
	}
}


任务间使用管道进行输入输出

原文:http://blog.csdn.net/u011345136/article/details/45228941

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!