在java中通过GUI停止正在运行的进程

前端之家收集整理的这篇文章主要介绍了在java中通过GUI停止正在运行的进程前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个执行TestNG自动化脚本的GUI程序.这意味着用户可以轻松配置某些设置并启动他们想要的自动化脚本.

我需要补充的一件事是能够立即停止正在运行的TestNG流程.像Eclipse中的那样,“终止”按钮会立即停止正在运行的任何内容.

这就是启动TestNG测试的代码如下所示:

public class ScriptRunner implements Runnable {

    public void runScript() {
        Thread testRun = new Thread(this);
        testRun.start();
    }

    @Override
    public void run() {
        //varIoUs other things are configured for this,//but they're not relevant so I left them out
        TestNG tng = new TestNG();

        //While this runs,varIoUs browser windows are open,//and it could take several minutes for it all to finish
        tng.run();
    }
}

根据评论,tng.run()可能需要几分钟才能完成,它正在执行几项操作,打开/关闭浏览器窗口等.

我怎样才能立即终止进程,就像从IDE运行应用程序一样?

编辑:

根据评论,我试图使用ServiceExecutor和shutDownNow()代码看起来像这样:

ExecutorService executorService = Executors.newFixedThreadPool(10);

public void runScript() {
    executorService.execute(this);
}

//this method gets called when I click the "stop" button
public void stopRun() {
    executorService.shutdownNow();
}

@Override
public void run() {
    //same stuff as from earlier code
}

解决方法

我最近在处理执行程序框架.我在这里列出了我的问题
http://programtalk.com/java/executorservice-not-shutting-down/

如果您正在执行某些IO操作,请小心执行程序服务可能不会立即关闭.如果你看到下面的代码,stopThread很重要,因为它告诉你的程序已经要求线程停止.你可以停止一些迭代你正在做什么.
我会像这样修改你的代码

public class MyClass {

private ExecutorService executorService;

private boolean stopThread = false;

public void start() {
   // gives name to threads
    BasicThreadFactory factory = new BasicThreadFactory.Builder()
             .namingPattern("thread-%d").build();
    executorService =  Executors.newSingleThreadExecutor(factory);
    executorService.execute(new Runnable() {
        @Override
        public void run() {
            try {
                doTask();
            } catch (Exception e) {
                logger.error("indexing Failed",e);
            }

        }
    });
    executorService.shutdown();
}

private void doTask()  {
    logger.info("start reindexing of my objects");
    List<MyObjects> listOfMyObjects = new MyClass().getMyObjects();
    for (MyObjects myObject : listOfMyObjects) {
        if(stopThread){ // this is important to stop further indexing
            return;
        }
        DbObject dbObjects = getDataFromDB();
        // do some task
    }
}



public void stop() {
    this.stopThread = true;
    if(executorService != null){
        try {
            // wait 1 second for closing all threads
            executorService.awaitTermination(1,TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

}

猜你在找的Java相关文章