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