1

我试图将所有小于 10000 的素数写入 PipedOutPutStream。当我执行程序时,它会打印到 1619。但程序仍在运行。如果我注释用于写入流的代码并执行程序,那么它会正确打印素数。谁能弄清楚为什么会这样?

public class PrimeThread implements Runnable {

    private DataOutputStream os;

    public PrimeThread(OutputStream out) {
        os = new DataOutputStream(out);
    }

    @Override
    public void run() {

        try {
            int flag = 0;
            for (int i = 2; i < 10000; i++) {
                flag = 0;
                for (int j = 2; j < i / 2; j++) {
                    if (i % j == 0) {
                        flag = 1;
                        break;
                    }
                }
                if (flag == 0) {
                    System.out.println(i);
                    os.writeInt(i);//if i comment this line its printing all the primeno
                    os.flush();
                }
            }
            os.writeInt(-1);
            os.flush();
            os.close();
        } catch (IOException iOException) {
            System.out.println(iOException.getMessage());
        }
    }
}

public class Main {

    public static void main(String[] args) {
        PipedOutputStream po1 = new PipedOutputStream();
        //PipedOutputStream po2 = new PipedOutputStream();
        PipedInputStream pi1 = null;
        //PipedInputStream pi2 = null;
        try {
            pi1 = new PipedInputStream(po1);
            //pi2 = new PipedInputStream(po2);
        } catch (IOException iOException) {
            System.out.println(iOException.getMessage());
        }

        Runnable prime = new PrimeThread(po1);
        Thread t1 = new Thread(prime, "Prime");
        t1.start();
//some code
}
}
4

1 回答 1

1

PipedOutPutStream的内部缓冲区溢出,在转储之前无法接受更多数据。在主线程中,从 读取PipedInputStream pi1,质数计算将继续进行。

于 2013-10-15T07:33:14.620 回答