这篇文章给大家介绍如何进行Java多线程循环相关的代码介绍,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
Java多线程循环需要我们不断的学习,有很多的问题一直是我们相互关心的。下面我们就来看看如何才能更好的使用这门编程语言。当每个迭代彼此独立,并且完成循环体中每个迭代的工作,意义都足够重大,足以弥补管理一个新任务的开销时,这个顺序循环是适合并行化的。
public<T> voidParallelRecursive(final Executorexec,List<Node<T>>nodes,Collection<T> results){ for(Node<T> n:nodes){ exec.execute(new Runnable(){ public void run(){ results.add(n.compute()); } }); parallelRecursive(exec,n.getChildren(),results); } } public<T>Collection<T>getParallelResults(List<Node<T>>nodes) throws InterruptedException{ ExecutorService exec=Executors.newCachedThreadPool(); Queue<T> resultQueue=newConcurrentLinkedQueue<T>(); parallelRecursive(exec,nodes,resultQueue); exec.shutdown(); exec.awaitTermination(Long.MAX_VALUE,TimeUnit.SECONDS); return reslutQueue; }
但是以上程序不能处理不存在任何方案的情况,而下列程序可以解决这个问题
public class PuzzleSolver<P,M>extendsConcurrentPuzzleSolver<P,M>{ ... privatefinal AtomicInteger taskCount=new AtomicInteger(0); protectedRunnable newTask(P p,M m,Node<P,M>n){ return new CountingSolverTask(p,m,n); } classCountingSolverTask extends SolverTask{ CountingSolverTask(P pos,Mmove,Node<P,M> prev){ super(pos,move,prev); taskCount.incrementAndGet(); } publicvoid run(){ try{ super.run(); } finally{ if (taskCount.decrementAndGet()==0) solution.setValue(null); } } } }
关于如何进行Java多线程循环相关的代码介绍就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。