我想在使用管道的线程之间实现非常简单的通信。
public class Main {
public static void main(String[] args) throws InterruptedException, IOException {
PipedReader reader = new PipedReader();
PipedWriter writer = new PipedWriter(reader);
CommitThread t1 = new CommitThread(reader);
t1.start();
for(int i = 0; i<10000; i++){
System.out.println("Main - Writing to pipe " + i);
writer.write("Number " + i);
writer.flush();
Thread.sleep(1000);
}
}
}
public class CommitThread extends Thread{
private PipedReader input;
public CommitThread(PipedReader input) {
this.input = input;
}
@Override
public void run() {
while(true){
try {
BufferedReader buffer = new BufferedReader(this.input);
while(true) {
String temp = buffer.readLine();
if(temp == null){
System.out.println("Commit - Empty");
this.input.close();
return;
}
System.out.println("Commit - Input from pipe is " + temp);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
我调试了程序,但似乎CommitThread没有从管道获取消息。调试器显示管道已填满,但CommitThread未读取数据并继续等待。
我认为这一定是一个非常小而且愚蠢的错误,但我无法找到它。有人能帮助我吗?
答案 0 :(得分:0)
看这里:BufferedReader doesn't return
如果您连接的服务器没有关闭连接,BufferedReader将挂起,等待下一行文字。
所以我认为这就是问题所在。只需尝试通过char
读取char