1

我真的需要这个网站上善良的向导的帮助。我在execute()我的AbstractHandler. 这项工作有一个进度监视器,一切正常,直到我尝试中止工作。

当用户单击取消按钮时,进度监视器屏幕会关闭,但在作业中启动的线程会继续在后台运行。调用cancel()作业不会停止子线程。呼叫interrupt()也无济于事。

public Object execute(ExecutionEvent event) throws ExecutionException {


    ...
    job = new Job("Doing my job") {

        @Override
        protected IStatus run(IProgressMonitor monitor) {
            monitor.beginTask("Running a length thread",10);
            monitor.worked(1);
            Thread unstoppableThread; //the pain in my neck


                    try {
                        unstoppableThread = new Thread() {
                            public void run() {

                                //A lengthy process
                            }

                        };

                    int i = 1;
                    while(unstoppableThread.isAlive()){

                        if(monitor.isCanceled()){
                            //job.cancel(); doesn't work
                            //IJobManager manager = Job.getJobManager();
                            //manager.cancel(job); doesn't work
                            //unstoppableThread.interrupt(); doesn't work too
                            return Status.CANCEL_STATUS; 
                        }

                        try {
                            if(i<8)monitor.worked(1);
                            i++;
                            TimeUnit.SECONDS.sleep(1);

                        }
                        catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }


            }finally{
               monitor.done(); 
            }

            return Status.OK_STATUS; 
        }                                        //end of Job#run()

    };                                           //end of Job block

    job.setUser(true);
    job.schedule();
    return null;
    }
4

1 回答 1

2

你需要“不可阻挡的线程”来配合;它需要定期检查自己的中断标志,并在它变为真时停止。然后在你的“取消”代码中,调用unstoppableThread.interrupt(),它就会真正起作用。

换句话说,run()你不可阻挡的线程的方法需要看起来像

public void run() {
    while (!Thread.interrupted()) {
        // Do a little work
    }
}
于 2013-06-07T14:30:33.130 回答