内容:通过输入/输出在线程间进行通信通常很有用。利用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(); } }
时间: 2024-10-18 09:50:33