我想創(chuàng)建一個程序來使用java中的線程計算通過控制臺輸入的數(shù)字的平均值。在主函數(shù)中,我從未從函數(shù) getAverage() 中獲得平均值的輸出。出了什么問題..當我調(diào)試時..程序終止但在正常運行中..當我輸入除雙精度值以外的任何內(nèi)容時它應該終止,但它不會發(fā)生。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(); }
在主功能中..不顯示平均值。線程不活動但未終止。為什么?
慕田峪4524236
2023-08-04 15:18:33