如何在java中跟踪和实现嵌套Runnable的取消选项

问题描述 投票:1回答:1

我正在使用一个使用ZMQ来处理请求的Java应用程序。我的代码有一些嵌套的Runnable,如下面的结构:

private class SomeRunnable implements Runnable {
    @Override
    public void run() {
        while (!stop) {
            try {
                createProcess();
            }
            catch (Exception e) {
                //handled
            }
        }
    }
}

public void createProcess(){
    ZMsg receivedRequest = receiveReq(); // wait for request
    Runnable workerRunnable = new WorkerRunnable(receivedRequest, this);
    Thread workerThread = new Thread(workerRunnable);
    workerThread.start();
}

因此,每次我使用Fiddler发送请求时,它都会创建新的WorkerRunnable并将zmq请求传递给它进行进一步处理。此WorkerRunnable定义为:

private class WorkerRunnable implements Runnable {
    @Override
    public void run() {
            try {
                // do something with received request
                switch(type) : 
                case EXECUTE:
                    startExecution(); // this will internally create one more thread
                    break;

                case STOP:
                    stopExecution();
                    break;                      
            }
            catch (Exception e) {
                //handled
            }
        }
    }
}

这是一个非常简单的工作流程:

  1. 我使用fiddler执行了一些请求。它将创建一个WorkerRunnable。
  2. 在下一个请求中,我想停止在步骤1中启动的WorkerRunnable

可能会发生我提出多个请求然后在其中我想要停止任何一个请求。如何跟踪所有WorkerRunnable以及如果请求阻止它们如何中断它们?我尝试了ExecutorService,但在这种情况下没有找到任何确切的方法来使用它。请建议正确的方法来做到这一点。

java multithreading runnable executorservice threadpoolexecutor
1个回答
0
投票

您是否考虑过在thread pool函数中使用createProcess()?如果您使用了池,那么您可以将Callable任务提交到池中,然后返回Future实例。然后,根据您实现Callable对象的方式,您可以使用Future.cancel()方法中止任务。

© www.soinside.com 2019 - 2024. All rights reserved.