我想创建一个程序来使用java中的线程计算通过控制台输入的数字的平均值。在主函数中,我从未从函数 getAverage() 中获得平均值的输出。出了什么问题..当我调试时..程序终止但在正常运行中..当我输入除双精度值以外的任何内容时它应该终止,但它不会发生。
import java.util.*;
public class P1
{
private AverageCalculator ac;
private boolean stop;
public Thread inputThread,averageThread;
public P1()
{
ac = new AverageCalculator();
new UserInteraction(ac);
new ToAverage(ac);
}
public void printAverage()
{
System.out.println("Average is " + ac.getAverage());
}
private class AverageCalculator{
private double average=0,sum=0;
private int i=0;
private boolean flag=false;
private double getAverage()
{
return average;
}
private synchronized void sum(double val) {
while(flag) {
try {
wait();
} catch(InterruptedException e) { System.out.println("Thread Interrputed"); }
}
sum += val;
i++;
flag = true;
notify();
}
private synchronized void calculateAverage()
{
while(!flag) {
try {
wait();
} catch(InterruptedException e) { System.out.println("thread interrupted"); }
}
average = (sum / i);
flag = false;
notify();
}
}
private class UserInteraction implements Runnable {
private AverageCalculator ac;
//private boolean take=true;
private double input=0;
Scanner s = new Scanner(System.in);
private UserInteraction(AverageCalculator ac) {
this.ac = ac;
inputThread = new Thread(this,"Input thread");
inputThread.start();
stop=false;
}
public void run()
{
System.out.println("Enter number: ");
while(!stop) {
if(s.hasNextDouble() == false) {
stop = true;
s.close();
}
弑天下
相关分类