Java 多线程通信之管道通信(pipe)及常见异常处理 (一)

2014-11-24 10:53:19 · 作者: · 浏览: 1

Java多线程之间要交换信息,有时只能用管道来完成,在使用管道通信时,经常会碰到“java - IOException: Read end dead”或者“java - IOException: Write end dead”的异常,下面针对这个问题作出一个简单的分析,首先是写了一个管道通信的demo供大家参考。程序如下:

[java] package com.csc.pipetest;

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

/**
* 管道通信demo
*
* @author csc
*
*/
public class PipeTest {

public static void main(String[] args) {

// 创建管道输出流
PipedOutputStream pos = new PipedOutputStream();
// 创建管道输入流
PipedInputStream pis = new PipedInputStream();
try {
// 将管道输入流与输出流连接 此过程也可通过重载的构造函数来实现
pos.connect(pis);
} catch (IOException e) {
e.printStackTrace();
}
// 创建生产者线程
Producer p = new PipeTest().new Producer(pos);
// 创建消费者线程
Consumer c = new Consumer(pis);
// 启动线程
p.start();
c.start();
}

// 生产者线程(与一个管道输入流相关联)
private class Producer extends Thread {
private PipedOutputStream pos;

public Producer(PipedOutputStream pos) {
this.pos = pos;
}

public void run() {
int i = 8;
// while (true) {//加入此句将出现“java - IOException: Read end dead”异常
try {
pos.write(i);
} catch (IOException e) {
e.printStackTrace();
}
// }

}
}

// 消费者线程(与一个管道输入流相关联)
private static class Consumer extends Thread {
private PipedInputStream pis;

public Consumer(PipedInputStream pis) {
this.pis = pis;
}

public void run() {
// while(true){//加入此句将出现“java - IOException: Write end dead”异常
try {
System.out.println(pis.read());
} catch (IOException e) {
e.printStackTrace();
}
// }

}
}
}

package com.csc.pipetest;

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

/**
* 管道通信demo
*
* @author csc
*
*/
public class PipeTest {

public static void main(String[] args) {

// 创建管道输出流
PipedOutputStream pos = new PipedOutputStream();
// 创建管道输入流
PipedInputStream pis = new PipedInputStream();
try {
// 将管道输入流与输出流连接 此过程也可通过重载的构造函数来实现
pos.connect(pis);
} catch (IOException e) {
e.printStackTrace();
}
// 创建生产者线程
Producer p = new PipeTest().new Producer(pos);
// 创建消费者线程
Consumer c = new Consumer(pis);
// 启动线程
p.start();
c.start();
}

// 生产者线程(与一个管道输入流相关联)
private class Producer extends Thread {
private PipedOutputStream pos;

public Producer(PipedOutputStream pos) {
this.pos = pos;
}

public void run() {
int i = 8;
// while (true) {//加入此句将出现“java - IOException: Read end dead”异常
try {
pos.write(i);
} catch (IOException e) {
e.printStackTrace();
}
// }

}
}

// 消费者线程(与一个管道输入流相关联)
private static class Consumer extends Thread {
private PipedInputStream pis;

public Consumer(PipedInputStream pis) {
this.pis = pis;
}

public void run() {
// while(true){//加入此句将出现“java - IOException: Write end dead”异常
try {
System.out.println(pis.read());
} catch (IOException e) {
e.printStackTrace();
}
// }

}
}
}
上面的程序是可以正确运行的,①若将第46行和第52行注释掉的代码