Package thread;
Import java.io.IOException;
Import Java.io.PipedInputStream;
Import Java.io.PipedOutputStream;
public class Communicatewhitpiping
{
public static void Main (string[] args) {
Creating a pipeline output stream
PipedOutputStream PipedOutputStream = new PipedOutputStream ();
To create a pipeline input inflow
PipedInputStream PipedInputStream = new PipedInputStream ();
try {
Connecting the pipeline stream to the output this process can also be implemented by overloading the constructor
Pipedoutputstream.connect (PipedInputStream);
} catch (IOException e) {
E.printstacktrace ();
}
Create a producer thread
Producer p = new Producer (PipedOutputStream);
Create a consumer thread
Consumer C = new Consumer (PipedInputStream);
Start thread
P.start ();
C.start ();
}
}
/**
* Producer threads (associated with a pipeline output stream)
*/
Class Producer extends Thread//dog
{
int x=0;
Private PipedOutputStream POS;
Public Producer (PipedOutputStream POS) {
This.pos = pos;
}
public void Run ()
{
while (true)
{
try {
Thread.Sleep (500);
} catch (Interruptedexception E1) {
TODO Auto-generated catch block
E1.printstacktrace ();
}
try {
Pos.write (this.x);
this.x=this.x+2;
} catch (IOException e)
{
E.printstacktrace ();
}
}
}
}
/**
* Consumer thread (associated with a pipeline input)
*/
Class Consumer extends Thread//cat
{int x=50;
Private PipedInputStream PiS;
Public Consumer (PipedInputStream PiS) {
This.pis = PiS;
}
public void Run ()
{
int DOGX = 0;
while (true)
{
try {
try {
Thread.Sleep (500);
} catch (Interruptedexception e) {
TODO Auto-generated catch block
E.printstacktrace ();
}
Dogx=pis.read ();
System.out.println ("Cat's position" +this.x);
System.out.println ("————————————— Dog's position" +DOGX);
this.x++;
if (dogx-this.x>=1)
{
System.out.println ("Dog exceeds the Cat");
}
} catch (IOException e)
{
E.printstacktrace ();
}
}
}
}
Java multithreaded communication channel (CAT and Dog race)