亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在主功能中..不顯示平均值。線程不活動但未終止。為什么?

在主功能中..不顯示平均值。線程不活動但未終止。為什么?

慕田峪4524236 2023-08-04 15:18:33
我想創建一個程序來使用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();                }
查看完整描述

1 回答

?
弒天下

TA貢獻1818條經驗 獲得超8個贊

我沒有完全調試您的代碼,但問題是您正在調用wait().?此方法將您的線程置于等待狀態,并且必須調用notify()notifyAll()才能喚醒您的線程。

查看完整回答
反對 回復 2023-08-04
  • 1 回答
  • 0 關注
  • 130 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號