Content: Communication between threads via input/output is often useful. Take advantage of the PipedWriter class (which allows tasks to be written to the pipeline) and the Pipedreader class (allowing different tasks to be read from the same pipeline). In the code below, sender and receiver represent two tasks that need to communicate with each other. Sender puts the data in writer and then sleeps for a while. However, receiver does not have sleep () and wait (). But when he calls read (), if there is no more data, the pipeline will block, and normal I/O cannot be interrupted.
Class Sender implements Runnable {private Random rand = new random;p rivate pipedwriter out = new PipedWriter ();p ublic PipedWriter Getpipedwriter () {return out;} @Overridepublic 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.prin TLN (e + "Sender Sleeo Interrupted");}} Class Receiver implements Runnable {private pipedreader in;public Receiver (sender sender) throws IOException {in = new Pip Edreader (Sender.getpipedwriter ());} @Overridepublic 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 ();}}
Use pipelines for input and output between tasks