import java.io.*; class PipedThreadsAnswer { public static void main(String[] args){ try{ PipedWriter pw = new PipedWriter(); PipedReader pr = new PipedReader( pw ); Consumer c1 = new Consumer("C1", pr, 2 ); //Consumer c2 = new Consumer("C2", pr ); Producer p1 = new Producer("P1", pw ); Producer p2 = new Producer("P2", pw ); Thread c1thread = new Thread(c1); Thread p1thread = new Thread(p1); Thread p2thread = new Thread(p2); c1thread.start(); p1thread.start(); p2thread.start(); c1thread.join(); p1thread.join(); p2thread.join(); pw.close();// pr.close();// System.out.println("All done"); // Remember that join might throw an interrupted exception //new Thread(c2).start(); }catch(Exception e){ System.out.println(e); } } } class Producer implements Runnable{ PrintWriter pw; String producerName; Producer(String name, Writer pipe){ producerName = name; pw = new PrintWriter( pipe ); } public void run(){ for(int i=0; i<50;i++){ try{Thread.sleep( (int)(Math.random()*50) );}catch(InterruptedException e){}; pw.println(producerName + " produced a " + i); } pw.println("STOP"); } } class Consumer implements Runnable{ BufferedReader br; String consumerName; int count; Consumer(String name, Reader pr, int count ){ consumerName = name; br = new BufferedReader( pr ); this.count = count; } public void run(){ try{ while ( count > 0){ String line = br.readLine(); if (line.equals("STOP") ) count--; else System.out.println(consumerName + " got: " + line); } System.out.println("Consumer " + consumerName + " stopped"); }catch(IOException e){ System.out.println(e); } } }