螺纹阵列的最佳实践(JAVA) [英] Best practice for thread arrays (java)

查看:184
本文介绍了螺纹阵列的最佳实践(JAVA)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在Java线程的一些经验,但我想知道...

I have some experience with threading in java, but I am wondering...

什么是存储多个线程在那里我可以单独和作为一个群体访问这些最佳做法?

What's the best practise to store multiple threads where I can access them both individually and as a group?

我自己的解决方案是创建一个 threadArray 类,但我自然会preFER本地类是更可靠。

My own solution is to create a threadArray class but naturally I would prefer a native class that is much more reliable.

在此先感谢!

修改

显然,功能的最佳方法非常重要的。好吧,我举一个例子:

Apparently the functionality is of great importance of the best method. Well, I'll give an example:

我已经得到了基本上都是通过大量的信息,同时搜索,因此我使用线程的应用程序。然而,每一个线程需要,所以我希望增加额外的参数来指定一个范围内执行只是整个操作的一部分。

I've got an application that basically searches through a lot of information at the same time hence I'm using threads. The threads however each need to perform just a part of the entire operation so I wish to add additional parameters to specify a range.

当一个线程完成它的特定的搜索也可以只是停止自然。然而,当一个线程找到一个结果,我希望停止所有线程和检索结果。

When a thread finishes it's specific search it can just stop naturally. When a thread finds a result however, I wish to stop all threads and retrieve that result.

帮助吗?

推荐答案

我会使用的ExecutorService 来管理我的线程池,并把<$ C $以某种形式收藏的加入,当我的主题池,我给C>未来取值。

I'd use an ExecutorService to manage my threads as a pool and put the Futures I am given when adding my Threads to the pool in some form of Collection.

在这种方式,您可以管理所有通过执行程序线程作为一个单元,并通过跟踪单个线程的未来

In this way you can manage all of the threads as one unit via the Executor and track individual threads through their Future.

编辑回应你的

您可以使用的 shutdownNow时方法的ExecutorService 中止所有正在运行的线程。

You can use the shutdownNow method of the ExecutorService to abort all running threads.

示例(不是一个解决问题的方法,但涵盖了使用最大效益执行人):

Example (not a solution to your problem but covers most benefits of using Executors):

// 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");
  }
}

这篇关于螺纹阵列的最佳实践(JAVA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆