1
問題如下:多個線程與管道流進行通信並使用PushbackInputStream
創建3個主題。
- 第一個將產生10張隨機數,
- 第二將總結偶數的這些10.
- 第三將總結奇數相同的10支隨機數的。
我的問題是:在第二個線程我讀所有的數字和他們推回到流,但是當第三線程想要從流中讀取,讀取第一個值是-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產生的隨機數:
線程1成品
線程2:偶數隨機數之和:26
線程2完成
t hread 3:奇數隨機數之和:0
線程3完成
主要完成。
爲什麼不使用兩個管道(一個用於evens,一個用於可能性),並讓線程1爲每個數字決定將其寫入哪個管道? – finnw
是的,這是可能的解決方案,謝謝。但我很好奇它是否可以使用pushbackinputstream來解決,程序中的錯誤是什麼? –