线程数组的最佳实践(java)
我在Java线程方面有一些经验,但我想知道…
存储多个线程的最佳实践是什么,我可以在其中单独或成组访问这些线程?
我自己的解决方案是创建一个threadArray
类,但是自然地,我希望使用更可靠的本机类。
提前致谢!
编辑
显然,功能对于最佳方法非常重要。好吧,我举一个例子:
我有一个基本上可以同时搜索大量信息的应用程序,因此我正在使用线程。但是,每个线程仅需要执行整个操作的一部分,因此我希望添加其他参数来指定范围。
当一个线程完成它的特定搜索时,它自然就会停止。但是,当线程找到结果时,我希望停止所有线程并检索该结果。
有帮助吗?
-
我会使用an
ExecutorService
来将我的线程作为一个池来管理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"); } }
-
线程数组的最佳实践(java)
2021-01-30 关注 0 浏览62 1答案
-
多线程最佳实践:约束任务newFixedThreadPool
2021-01-30 关注 0 浏览68 1答案
-
安全地引发事件线程-最佳实践
2021-02-02 关注 0 浏览81 1答案
-
查找Java枚举的最佳实践
2021-01-29 关注 0 浏览104 1答案
-
Java 中,编写多线程程序的时候你会遵循哪些最佳实践?
2021-10-21 关注 0 浏览205 1答案
-
Java连接池最佳实践?
2021-01-29 关注 0 浏览119 1答案
-
Java:静态抽象(再次)-最佳实践
2021-01-29 关注 0 浏览78 1答案
-
在多线程环境中使用HttpClient的最佳实践
2021-01-31 关注 0 浏览93 1答案
-
(Java)包组织有最佳实践吗?
2022-07-28 关注 0 浏览12 1答案
-
最佳实践:Java静态非最终变量
2021-01-30 关注 0 浏览67 1答案