I am writing a simple multithreaded
application that involves three threads:
Thread-1
, Thread-2
and main
.
Thread-1
is a random number
generator class that produces random doubles
and feeds to Thread-2
.
Thread-2
consumes the numbers to calculate the average .I have used PipedOutputStream
that Thread-1
feeds with random numbers
. Thread-2
uses PipedInputStream
to eat up the random numbers
.
The question is::
if the average exceeds 1E5 in Thread-2
, I want to signal Thread-1
to stop producing numbers. I have a boolean flag
in Thread-1
that needs to be turned on. How can I achieve this?
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.Random;
//
class NumGen extends Thread {
PipedOutputStream pos;
DataOutputStream dos;
boolean isDone=false;
public NumGen(PipedOutputStream pos){
this.pos=pos;
dos=new DataOutputStream(pos);
}
public void run(){
while (!isDone){
Random rand = new Random();
try {
dos.writeDouble(rand.nextDouble()+100.0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class RunningAvg extends Thread {
PipedInputStream pis;
DataInputStream dis;
Double avg;
int count;
Double runningTotal;
public RunningAvg(PipedInputStream pis){
this.pis=pis;
dis=new DataInputStream(pis);
runningTotal=0.0;
avg=0.0;
}
public void run(){
try {
while (dis.available()>0){
count+=1;
runningTotal+=dis.readDouble();
avg=runningTotal/count;
System.out.printf("The average in count no : %s is %s%n",count,avg);
//if avg>1E5
//set NumGen.isDone=true
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class InterThreadComm {
public static void main(String[] args){
try {
PipedOutputStream pos= new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pos);
NumGen ng = new NumGen(pos);
RunningAvg ra = new RunningAvg(pis);
ng.start();
ra.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
PS: The code as it is runs forever without printing anything on console which I am yet to figure out why!!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…