Java 多线程 通信 通道 (猫狗赛跑)

package thread;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class CommunicateWhitPiping
{
public static void main(String[] args) {
// 创建管道输出流
PipedOutputStream pipedOutputStream = new PipedOutputStream();
// 创建管道输入流
PipedInputStream pipedInputStream = new PipedInputStream();
try {
// 将管道输入流与输出流连接 此过程也可通过重载的构造函数来实现
pipedOutputStream.connect(pipedInputStream);
} catch (IOException e) {
e.printStackTrace();
}
// 创建生产者线程
Producer p = new Producer(pipedOutputStream);
// 创建消费者线程
Consumer c = new Consumer(pipedInputStream);
// 启动线程
p.start();
c.start();
}
}

/**
* 生产者线程(与一个管道输出流相关联)
*/
class Producer extends Thread //狗
{
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 自动生成的 catch 块
e1.printStackTrace();
}



try {

pos.write(this.x);
this.x=this.x+2;
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}

/**
* 消费者线程(与一个管道输入流相关联)
*/
class Consumer extends Thread //猫
{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 自动生成的 catch 块
e.printStackTrace();
}



dogx=pis.read();
System.out.println("猫的位置"+this.x);

System.out.println("—————————————狗的位置"+dogx);

this.x++;
if(dogx-this.x>=1)
{
System.out.println("狗超过了猫");
}

} catch (IOException e)
{
e.printStackTrace();
}
}

}
}

posted on 2017-04-29 22:57  紫夜星辰  阅读(908)  评论(0编辑  收藏  举报