扫二维码与项目经理沟通
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流
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多线程方案关键代码的详细介绍。
【编辑推荐】

我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流