如何在java中停止,暂停,取消线程

时间:2012-03-22 20:43:27

标签: java multithreading

我正在使用java开发一个应用程序,它启动一些执行某些工作的线程并使用JTable更新JProgressBar。 我在JPopupMenu上开发了一个JTable JMenuItem

  • 暂停
  • 停止
  • 取消
  • 恢复

所以我希望能够做到。

当用户在JTable中添加新主题时,我将该主题保存在ArrayList<Thread>中,所以我必须实现

stop.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {

            }
        });

和另一个..

所以我尝试,假设我有当前线程的索引:

Thread t = working.get(selectedThread); //where working is my `ArrayList<Thread>`
t.interrupt();

但没有..它继续工作...... 所以我试试:

try {
                        working.get(actualRow).wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(PannelloRicerca.class.getName()).log(Level.SEVERE, null, ex);
                    }

但是IllegalStateMonitorException让我wait(),所以我不知道该怎么做..有人能帮帮我吗?

2 个答案:

答案 0 :(得分:1)

Thread.interrupt()调用仅设置Thread上的中断位,并导致任何waitsleep次调用InterruptedException。它并没有像许多人期望的那样取消线程的执行。

您可以在这样的线程中测试中断位:

while (!Thread.currentThread().isInterrupted()) {
   ...
}

人们停止线程的典型方法是拥有AtomicBoolean(或volatile boolean)并执行以下操作:

AtomicBoolean running = new AtomicBoolean(true);
while (running.set()) {
    ...
}

...
// then in the other thread (like the main thread) you stop the thread by:
runner.set(false);

您收到IllegalStateMonitorException,因为您正在调用wait,而不是在您正在等待的对象的synchronized块内。您需要执行以下操作:

Thread t = working.get(actualRow);
synchronized (t) {
    t.wait();
}

虽然我不确定那是你想要的。也许你想加入等待它完成的线程?

   working.get(actualRow).join();

答案 1 :(得分:1)

IllegalStateMonitorException是因为线程只能在它拥有的对象中等待(我不记得它是否是正确的术语)。

您需要先通过同一个对象进行同步,以确保没有其他人在等待此对象。

 synchronize (working.get(actualRow)) {
   working.get(actualRow).wait(); 
 }
相关问题