Java中怎么处理多线程

本篇文章为大家展示了Java中怎么处理多线程,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

创新互联建站专注为客户提供全方位的互联网综合服务,包含不限于做网站、成都网站制作、沙湾网络推广、重庆小程序开发公司、沙湾网络营销、沙湾企业策划、沙湾品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们最大的嘉奖;创新互联建站为所有大学生创业者提供沙湾建站搭建服务,24小时服务热线:18982081108,官方网址:www.cdcxhl.com

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);  }  }  publicCollectiongetParallelResults(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 PuzzleSolverextendsConcurrentPuzzleSolver{  ...  privatefinal AtomicInteger taskCount=new AtomicInteger(0);  protectedRunnable newTask(P p,M m,Noden){  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://ybzwz.com/article/jgcoph.html