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

我有一些java的线程经验,但我想知道……

存储多个线程的最佳实践是什么?我可以单独或作为一组来访问它们?

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

提前致谢!


编辑

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

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

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

这有帮助吗?

我使用ExecutorService来管理我的线程作为一个池,并在将某些forms的Collection Threads添加到池中时给出了Future

通过这种方式,您可以通过Executor将所有线程作为一个单元进行管理,并通过Future跟踪各个线程。

编辑以回应您的

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

示例(不是您的问题的解决方案,但涵盖了使用Executors的大部分好处):

 // Thread pool for the collectors. ExecutorService threads = Executors.newFixedThreadPool(MAX_THREADS); ... // Futures of all collectors running in the pool. ConcurrentLinkedQueue collectors = new ConcurrentLinkedQueue(); ... // Make my Callable. Callable 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 deadThreads = new LinkedList(); // 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"); } } 

我只会使用一个线程池,更具体地说是一个线程池执行器 。 这将维护一个线程缓存供您使用,尽管您将无法按需访问特定线程。

我经常简单地将Thread引用放在标准容器中。

容器的选择取决于您对对象的确切要求。

同步你的写作,你很好。 除非你做一些特殊或不寻常的事情,否则没有更多的东西。 你可以通过修改你的代码只允许一个线程一次写入,或者只有一个线程完成所有的写操作。

如果您通过多次写访问覆盖基础,那么“本机”类将无法为您提供更高的可靠性。

我不确定这条路径的年龄,但涵盖基本同步,multithreading访问和其他一些事情。

为什么不使用Java的Collection Framework?

我使用Map来存储线程,目的是为了在线游戏,所以我将对客户端线程的引用存储在地图中,其中字符名称(唯一的)作为线程的关键。

只需选择最适合您需求的系列。

除此之外,您还可以使用Collections类中的方法根据需要创建Collections同步版本。