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();
}
}

}
}

转载于:https://www.cnblogs.com/-sheng/p/6786559.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值