我想做一個簡單的應用程序。但我想用按鈕停止線程。這段代碼不起作用。我看所有的網站都是這樣的。我不明白為什么不工作。線程以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();
沒有關閉正確的線程。
添加回答
舉報
0/150
提交
取消