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

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

使用 Jbutton 停止線程 (Java)

使用 Jbutton 停止線程 (Java)

德瑪西亞99 2023-08-16 18:04:29
我想做一個簡單的應用程序。但我想用按鈕停止線程。這段代碼不起作用。我看所有的網站都是這樣的。我不明白為什么不工作。線程以btnStart. btnStop不工作。我編寫了 stopThread() 函數來停止。這該怎么辦?任何想法?private volatile boolean isRunning;==============     private void stopThread() {        isRunning=false;        Thread.currentThread().interrupt();    }==============     private final void runThread() {        new Thread() {            public void run() {                while (isRunning) {                    try {                         Random r = new Random();                         islemler[0] = "+";                         islemler[1] = "-";                         islemler[2] = "*";                         islemler[3] = "/";                         for (int i = 0; i <10; i++) {                             islem1 = islemler[r.nextInt(4)];                             islem2 = islemler[r.nextInt(4)];                             islem3 = islemler[r.nextInt(4)];                             islem4 = islemler[r.nextInt(4)];                             txt1.setText("1"+islem1+"1");                             txt2.setText("1"+islem2+"1");                             txt3.setText("1"+islem3+"1");                             txt4.setText("1"+islem4+"1");                             Thread.sleep(150);                             Thread.sleep(50);                         }                    } catch (Exception e) {                        e.printStackTrace();                    }                }            }        }.start();    }==============btnStart.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent e) {                isRunning=true;                runThread();          **This part is working**            }        });==============btnStop = new JButton("Stop");        btnStop.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent e) {                stopThread();         **But this part is not working. Can you help??**            }        });
查看完整描述

1 回答

?
九州編程

TA貢獻1785條經驗 獲得超4個贊

問題

您打開了兩個線程,如果您為用戶界面預留了一個線程,則可能是三個。

第一個線程是程序啟動的線程,第二個線程是創建隨機對象和 for 循環的線程。當您調用“停止線程”時,您是從主線程或用戶界面的第三個線程執行此操作。

這意味著

????Thread.currentThread().interrupt();

沒有關閉正確的線程。

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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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