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();
}
}
};
}
最新文章
- Qt for Android开发环境搭建及测试过程记录
- C语言中,头文件和源文件的关系(转)
- Java 分页通用
- Lintcode: Rotate String
- MFC编程入门之前言
- SICP 换零钱的迭代版本
- HDU 1718 Rank counting sort解法
- Windows版 mysql 5.7.16安装
- swift 深入理解Swift的闭包
- C#之重定向输入输出
- 在IIS Express中调试时无法读取配置文件
- Qt容器类(总结)(新发现的QQueue和QStack,注意全都是泛型)
- APICloud界面间跳转
- MySQL 单个表锁死 对查询语句无响应
- datagridview 行高列宽的自动设置
- Text Justification 文本左右对齐
- 深入理解LInux内核-进程通信
- LeetCode——Invert Binary Tree
- RxJava Subject
- CAS总结