gpt4 book ai didi

java - 如何正确使用ExecutorService来管理并发运行的SwingWorker数量?

转载 作者:行者123 更新时间:2023-11-30 09:08:42 29 4
gpt4 key购买 nike

我正在根据需要建立的多个连接生成 SwingWorker。我试图做到这一点,以便我设置固定数量的最大并发 SwingWorker,并且当其中一个完成时另一个开始(或者如果许多已经完成则启动许多其他)。基于http://java.dzone.com/articles/multi-threading-java-swing我正在像这样设置基本的 SwingWorker:

SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>() {
@Override
protected Boolean doInBackground() throws Exception {

System.out.println("One SwingWorker just ran! ");
}

return true;
}

// Can safely update the GUI from this method.
protected void done() {

boolean status;
try {
// Retrieve the return value of doInBackground.
status = get();
statusLabel.setText("Completed with status: " + status);
} catch (InterruptedException e) {
// This is thrown if the thread's interrupted.
} catch (ExecutionException e) {
// This is thrown if we throw an exception
// from doInBackground.
}
}


};

worker.execute();


现在我不确定如何实现我上面描述的机制。

来自 https://stackoverflow.com/a/8356896/988591我看到我可以使用 ExecutorService 来执行 SwingWorker 的实例,并且该接口(interface)还允许设置线程数:

int n = 20; // Maximum number of threads
ExecutorService threadPool = Executors.newFixedThreadPool(n);
SwingWorker w; //don*t forget to initialize
threadPool.submit(w);

我认为这就是我需要的,但我不知道如何将整个东西组合在一起(..我对 Java 也很陌生..)。有人可以在实现过程中指导我吗?说在顶部我有 int totalTask​​ = 100; 也许这只是一些循环的问题,但我似乎找不到任何真正容易理解的例子,我就是不能完全让我全神贯注......我会很感激一些帮助!谢谢。


更新:我以这种方式设置了 ExecutorService:

ExecutorService executorService = Executors.newFixedThreadPool(500);

for (int i = 0; i < 20 ; i++) {

executorService.submit(worker);
//I tried both...
//executorService.execute(worker);
}


并且我删除了在上面的 SwingWorker 之后调用的 worker.execute() 但是控制台的输出只是一个“One SwingWorker just ran!” 行,这是怎么回事?我做错了什么?

最佳答案

你会做这样的事情:

  • 使用固定的线程池启动 executorservice显示。
  • 在循环中创建您的可运行对象。您需要多少个可运行对象。
  • 您可以有 50 个线程和 5000 个可运行对象。第一个50后
    runnables,无论哪个线程空闲,都将执行第 51 个任务,并且
    等等。
  • 使用您的 Runnable 调用 executorservice 的执行方法。
  • 完成所有操作后,关闭执行程序服务。

像这样:

ExecutorService executorService = Executors.newFixedThreadPool(500);

for (long i = 0; i < 1000000; i++) {
Runnable populator = new YourRunnable();
executorService.execute(populator);
}
executorService.shutdown();
while(!executorService.isTerminated()){
}

isTerminated 可用于检查 executorServices 是否确实已关闭。因为即使在调用 shutdown() 方法之后您也可以有多个执行程序线程在运行(因为它们还没有完成任务),所以 while 循环就像一个 wait 调用。

还有一件关键的事情:无论您想传递给 ExecutorService,它都必须是一个 Runnable 实现。在您的情况下,您的 SwingWorker 必须是 Runnable。

关于java - 如何正确使用ExecutorService来管理并发运行的SwingWorker数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23394172/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com