线程数组的最佳实践(java)

线程数组的最佳实践(java),第1张

线程数组的最佳实践(java)

我会使用

anExecutorService
来将我的线程作为一个池来管理
Future
,并
Threads
以某种形式将我添加到池中时得到的s放入
Collection。

这样,您就可以通过执行器将所有线程作为一个单元进行管理,并通过它们的跟踪单个线程Future。

根据您的要求进行编辑

您可以使用的

shutdownNow
方法
ExecutorService
来中止所有正在运行的线程。

示例(不是解决问题的方法,但涵盖了使用执行程序的大多数好处):

// Thread pool for the collectors.ExecutorService threads = Executors.newFixedThreadPool(MAX_THREADS);...// Futures of all collectors running in the pool.ConcurrentlinkedQueue<Future> collectors = new ConcurrentlinkedQueue<Future>();...// Make my Callable.Callable<Void> c = new FileListCollector(path, recurse, filter);// Start it up and keep track of it so we can find out when it has finished.collectors.add(threads.submit(c));...// Called when nothing in queue.private void checkForFinished() {  // Count the running threads.  int runningThreads = 0;  try {    // Track dead ones to remove.    List<Future> deadThreads = new linkedList<Future>();    // Walk all collectors.    for (Future f : collectors) {      // I've seen f being null once. No idea how.      if (f != null) {        // If it's not done then it's running.        if (!f.isDone()) {          // Count it.          runningThreads += 1;        } else {          // Mark for deletion.          deadThreads.add(f);        }      }    }    // Clear dead threads - just to be tidy.    collectors.removeAll(deadThreads);  } catch (ConcurrentModificationException cme) {    // Probably a new thread has been started while I was checking!    // Therefore almost certainly NOT all finished.    runningThreads += 1;  }  // If no threads are left, we're done.  if (runningThreads == 0) {    // Finished! Close everything down.    close();  }}// Close down the whole system.public void close() {  // Use the fileQueue state to indicate closed.  if (!fileQueue.isClosed()) {    // Close the queue ... unblocking all collectors (I hope).    fileQueue.close();    // Shut them down agressively as this may be called by user prematurely as well as by me.    threads.shutdownNow();    // Wait until all is done.    boolean terminated = false;    do {      try {        // Wait up to 1 second for termination.        terminated = threads.awaitTermination(1, TimeUnit.SECONDS);      } catch (InterruptedException ex) {        // Ignore the interrupt! If I exit here we will probably leak.      }    } while (!terminated);    log("! All done");  }}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5429626.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存