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

发布于 2021-01-30 16:43:14

我在Java线程方面有一些经验,但是我想知道……

存储多个线程的最佳实践是什么,我可以在其中
单独或成组访问这些线程?

我自己的解决方案是创建一个threadArray类,但是自然地,我
更喜欢一个可靠得多的本机类。

提前致谢!

编辑

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

我有一个基本上可以同时搜索大量信息的应用程序,
因此我正在使用线程。但是,每个线程
仅需要执行整个操作的一部分,因此我希望添加其他
参数来指定范围。

当一个线程完成它的特定搜索时,它自然就会停止。
但是,当一个线程找到结果时,我希望停止所有线程并检索该
结果。

有帮助吗?

关注者
0
被浏览
62
1 个回答
  • 面试哥
    面试哥 2021-01-30
    为面试而生,有面试问题,就找面试哥。

    我会使用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");
      }
    }
    


推荐阅读
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看