我试图将所有小于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
}
}

最佳答案

PipedOutPutStream的内部缓冲区溢出,并且在转储之前不能接受更多数据。在主线程中,从PipedInputStream pi1读取,素数计算将继续。

07-26 00:33