我试图将小于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
}
}
答案 0 :(得分:1)
PipedOutPutStream
的内部缓冲区溢出,在转储之前无法接受更多数据。在主线程中,从PipedInputStream pi1
读取,并且将继续进行素数计算。