Java多线程循环需要我们不断的学习,有很多的问题一直是我们相互关心的。下面我们就来看看如何才能更好的使用这门编程语言。当每个迭代彼此独立,并且完成循环体中每个迭代的工作,意义都足够重大,足以弥补管理一个新任务的开销时,这个顺序循环是适合并行化的。

成都创新互联公司专注于临武网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供临武营销型网站建设,临武网站制作、临武网页设计、临武网站官网定制、成都微信小程序服务,打造临武网络公司原创品牌,更为您提供临武网站排名全网营销落地服务。
- public
 voidParallelRecursive(final Executorexec, 
List>nodes,Collection results){ - for(Node
 n:nodes){ - exec.execute(new Runnable(){
 - public void run(){
 - results.add(n.compute());
 - }
 - });
 - parallelRecursive(exec,n.getChildren(),results);
 - }
 - }
 - public
 Collection getParallelResults(List >nodes) - throws InterruptedException{
 - ExecutorService exec=Executors.newCachedThreadPool();
 - Queue
 resultQueue=newConcurrentLinkedQueue (); - parallelRecursive(exec,nodes,resultQueue);
 - exec.shutdown();
 - exec.awaitTermination(Long.MAX_VALUE,TimeUnit.SECONDS);
 - return reslutQueue;
 - }
 
但是以上程序不能处理不存在任何方案的情况,而下列程序可以解决这个问题
- public class PuzzleSolver
 extendsConcurrent
PuzzleSolver{
- ...
 - privatefinal AtomicInteger taskCount=new AtomicInteger(0);
 - protectedRunnable newTask(P p,M m,Node
 n){
- return new CountingSolverTask(p,m,n);
 - }
 - classCountingSolverTask extends SolverTask{
 - CountingSolverTask(P pos,Mmove,Node
 prev){
- super(pos,move,prev);
 - taskCount.incrementAndGet();
 - }
 - publicvoid run(){
 - try{
 - super.run();
 - }
 - finally{
 - if (taskCount.decrementAndGet()==0)
 - solution.setValue(null);
 - }
 - }
 - }
 - }
 
以上就是对Java多线程循环的相关介绍。希望大家有所收获。
Copyright © 2009-2022 www.wtcwzsj.com 青羊区广皓图文设计工作室(个体工商户) 版权所有 蜀ICP备19037934号