问题如下:
创建3个主题。
我的问题是:在第二个线程中我读取了所有数字并将它们推回到流中,但是当第三个线程想要从流中读取时,读取的第一个值是-1?
以下是代码:
//main program
import java.io.*;
public class anonymous {
public static void main(String[] args) throws IOException, InterruptedException {
final PipedOutputStream out= new PipedOutputStream();
final PipedInputStream in= new PipedInputStream(out);
Thread1 th1 = new Thread1(out);
Thread2 th2 = new Thread2(in);
Thread3 th3 = new Thread3(in);
Thread t1 = new Thread(th1);
Thread t2 = new Thread(th2);
Thread t3 = new Thread(th3);
t1.start();
t2.start();
t2.join();
t3.start();
t3.join();
System.out.println("main finished.");
}
}
//Thread1
import java.io.*;
import java.util.Random;
public class Thread1 implements Runnable{
PipedOutputStream out=null;
Random r = new Random();
public Thread1(PipedOutputStream send){
this.out = send;
}
public void run(){
int num;
System.out.println("thread 1 generated random numbers: ");
try{
for ( int i=0; i<10; i++)
{
num=r.nextInt(10);
System.out.print(num + " ");
out.write(num);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("\nthread 1 finished");
}
}
//Thread2
import java.io.*;
public class Thread2 implements Runnable{
PipedInputStream in=null;
public Thread2( PipedInputStream get){
this.in = get;
}
public void run(){
PushbackInputStream push = new PushbackInputStream(in , 10);
//PushbackInputStream takes an InputStream and it will read the first 10 bytes
// in the stream and push them back to the stream
try {
byte[] byteArr = new byte[10];
int i, sum=0, idx=0;
i=push.read();
while (i != -1)
{
if( i%2 == 0)
sum += i;
byteArr[idx]=( byte) i;
i=push.read();
idx++;
}
push.unread(byteArr,0 , 10);
System.out.println("thread 2: the sum of even random numbers: " + sum);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("thread 2 finished");
}
}
//Thread3
import java.io.*;
public class Thread3 implements Runnable{
PipedInputStream in;
public Thread3( PipedInputStream get){
this.in = get;
}
public void run(){
try {
int i, sum=0;
i=in.read();
while (i != -1)
{
if( i%2 == 1)
sum += i;
i=in.read();
}
System.out.println("thread 3: the sum of odd random numbers: " + sum);
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e){
e.printStackTrace();
}
System.out.println("thread 3 finished");
}
}
输出如下:
线程1生成随机数:
4 8 7 5 6 8 7 1 0 5
线程1完成了 线程2:偶数随机数的总和:26
线程2完成了 线程3:奇数随机数的总和:0
线程3完成了 主要完成。
答案 0 :(得分:3)
您应该在第二个和第三个流之间使用另一个管道,而不是滥用后推功能。