user1958241
user1958241

Reputation:

PipedOutputStream in Java

Am trying to write all the prime numbers less than 10000 into a PipedOutPutStream. When I execute the program it prints till 1619. But the the program is still running. If I comment the code for writing into the stream and execute the program then it prints the prime numbers correctly.Can anyone figure out why is this happening ?

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
}
}

Upvotes: 1

Views: 198

Answers (1)

Alexei Kaigorodov
Alexei Kaigorodov

Reputation: 13515

PipedOutPutStream's internal buffer is overflowed and cannot accept more data until it is dumped. In the main thread, read from PipedInputStream pi1, and prime number calculation would go on.

Upvotes: 1

Related Questions