java 利用管道实现线程间通信

package com.lb;

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

public class Test2 {
private PipedInputStream is = null;
private PipedOutputStream os = null;
private boolean run = true;

public static void main(String[] args) {
// TODO Auto-generated method stub
new Test2().t();
}

public void t() {
read.start();
read2.start();
send.start();
}

public Test2() {
is = new PipedInputStream(1);
os = new PipedOutputStream();
try {
is.connect(os);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

private Thread read = new Thread() {
byte[] buff = new byte[1024];

public void run() {
try {
while (run) {
is.read(buff);
System.out.println(Thread.currentThread().getName() + "-->" + new String(buff));
Arrays.fill(buff, (byte) 0x00);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};

private Thread read2 = new Thread() {
byte[] buff = new byte[1024];

public void run() {
try {
while (run) {
is.read(buff);
System.out.println(Thread.currentThread().getName() + "-->" + new String(buff));
Arrays.fill(buff, (byte) 0x00);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private Thread send = new Thread() {
public void run() {
try {
while (run) {

String context = "";
context = String.valueOf(((int) (Math.random() * 100)) % 7);
Thread.sleep(500);
System.out.println("snd " + Thread.currentThread().getName() + "-->" + context);
os.write(context.getBytes());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}

posted @ 2019-05-11 13:48  ForMeDream  阅读(747)  评论(0编辑  收藏  举报