我想做一個(gè)簡(jiǎn)單的應(yīng)用程序。但我想用按鈕停止線程。這段代碼不起作用。我看所有的網(wǎng)站都是這樣的。我不明白為什么不工作。線程以btnStart. btnStop不工作。我編寫了 stopThread() 函數(shù)來(lái)停止。這該怎么辦?任何想法?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貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超4個(gè)贊
問(wèn)題
您打開(kāi)了兩個(gè)線程,如果您為用戶界面預(yù)留了一個(gè)線程,則可能是三個(gè)。
第一個(gè)線程是程序啟動(dòng)的線程,第二個(gè)線程是創(chuàng)建隨機(jī)對(duì)象和 for 循環(huán)的線程。當(dāng)您調(diào)用“停止線程”時(shí),您是從主線程或用戶界面的第三個(gè)線程執(zhí)行此操作。
這意味著
????Thread.currentThread().interrupt();
沒(méi)有關(guān)閉正確的線程。
添加回答
舉報(bào)
0/150
提交
取消