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