如何在Java中停止,暂停,取消线程 [英] How to stop, pause, cancel a thread in java

查看:541
本文介绍了如何在Java中停止,暂停,取消线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java开发一个应用程序,该应用程序将启动执行某些工作的线程并用JProgressBar更新JTable. 我在具有某些JMenuItemJTable上开发了JPopupMenu:

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

所以我希望能够做到.

当用户在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);
                    }

但是它让我在wait()上获得了IllegalStateMonitorException,所以我不知道该怎么办..有人可以帮助我吗?

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

您需要先由同一对象进行同步,以确保没有其他人在等待该对象.

 synchronize (working.get(actualRow)) {
   working.get(actualRow).wait(); 
 }

i'm developing an app in java that launches some threads that do some jobs and update a JTable with a JProgressBar. I develope a JPopupMenu on the JTable that has some JMenuItem:

  • Pause
  • Stop
  • Cancel
  • Resume

So i want to be able to do it.

When user add new thread in JTable i save the thread in a ArrayList<Thread>, so i have to implement

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

            }
        });

and the other..

so i try , with the hypothesis that i have the index of current thread:

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

but nothing.. it continue working... so i try:

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

but it get me IllegalStateMonitorException on wait(), so i don't know how to do.. can someone help me?

解决方案

The IllegalStateMonitorException is because a thread can only wait in an object it it 'owns' (I don't remember if it is the right term) it.

You need to synchronize by the same object first, in order to ensure that nobody else is already waiting on this object.

 synchronize (working.get(actualRow)) {
   working.get(actualRow).wait(); 
 }

这篇关于如何在Java中停止,暂停,取消线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆