Java多线程方案在不断的完善中已经找到了自己的各种缺点,下面我们就来看看如何才能更好的学习相关问题。希望大家在不断的学习中有所收获,自由在不断的学习中才能更好的进行掌握Java多线程方案。
1、当每个迭代彼此独立,并且完成循环体中每个迭代的工作,意义都足够重大,足以弥补管理一个新任务的开销时,这个顺序循环是适合并行化的。
2、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
extendsConcurrentPuzzleSolver
{
- ...
- 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多线程方案关键代码的详细介绍。
【编辑推荐】
分享名称:Java多线程方案如何处理关键代码
本文网址:http://www.csdahua.cn/qtweb/news21/365071.html
网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网