Java multithreaded communication channel (CAT and Dog race)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.