通过java中的管道流丢失数据

时间:2014-01-19 02:25:22

标签: java string multithreading io stream

我正在为Java中的并行和并发编程类做实验。现在,我正在尝试使用管道流在线程之间进行通信。我正在使用java.io库中的PipedWriter和PipedReader。出于某种原因,在线程之间进行通信时,我发送的一些消息会丢失。

更具体地说,这是一个截图。

http://screencloud.net/v/bicK

正如你所看到的,我也得到了一些奇特的符号,这通常不太好用:)

这是我的线程类

package lab2_string;

import java.io.*;

public class StringRunnable implements Runnable{

    int threadNr;
    PipedReader in;
    PipedWriter out;
    String msg = "";
    @Override
    public void run() {
        readStream();
        System.out.println("Thread nr: " + threadNr);
        System.out.println("Message: " + msg);
        writeToStream();
    }

    public StringRunnable(PipedReader rs, PipedWriter ws, int threadNr){
        try{
            out = ws;
            in = rs;
            this.threadNr = threadNr;
        }catch (Exception e) {
            System.out.println("Error:" + e);
        }
    }

    public void writeToStream(){
        try{
            out.write(msg);
            out.flush();
            out.close();
        }catch (Exception e) {
            System.out.println("Error:" + e);
        }
    }


    public void readStream(){
        try{
            while(in.read()!=-1){
                char c = (char) in.read();
                msg = msg + c;
            }in.close();
        }catch (Exception e) {
            System.out.println("Error:" + e);
        }
    }

}

我的主程序课

package lab2_string;

import java.io.*;

public class Lab2 {

    public static void main(String[] args) {
        try{

            PipedWriter pwOut1 = new PipedWriter();
            PipedReader pwIn1 = new PipedReader(pwOut1);
            PipedWriter pwOut2 = new PipedWriter();
            PipedReader pwIn2 = new PipedReader(pwOut2);
            PipedWriter pwOut3 = new PipedWriter();

            Thread t1;
            Thread t2;

            t1 = new Thread(new StringRunnable(pwIn1,pwOut2,1));
            t2 = new Thread(new StringRunnable(pwIn2,pwOut3,2));
            t1.start();
            t2.start();

            pwOut1.write("Andrew");
            pwOut1.flush();
            pwOut1.close();


        }catch (Exception e) {
            System.out.println("Error:" + e);
        }

    }

}

请帮助我了解导致此问题的原因,以及如何解决问题!

1 个答案:

答案 0 :(得分:2)

你的in.read()调用会被执行两次,并且只在看起来存储在变量中。

public void readStream(){
        try{
            while(in.read()!=-1){
                char c = (char) in.read();
                msg = msg + c;
            }in.close();
        }catch (Exception e) {
            System.out.println("Error:" + e);
        }
    }

请注意,在while循环中调用in.read()(使in.read()返回的char不存储在c变量中并跳过该字符),

更好的例子可能类似于......

try{
    char c;
    while((c = (char)in.read()) != -1) {
        msg += c;
    }
    in.close();
} catch(Exception e){
    System.out.println("Error: " + e);
}

悟性?