当前位置: 首页 > news >正文

高级网站开发工信部百度搜索引擎关键词

高级网站开发工信部,百度搜索引擎关键词,免费公众号排版编辑器,wordpress 修订版本号我自己面试时被问过两次多任务并行相关的问题: 假设现在有10个任务,要求同时处理,并且必须所有任务全部完成才返回结果 这个面试题的难点是: 既然要同时处理,那么肯定要用多线程。怎么设计多线程同时处理任务呢&…

我自己面试时被问过两次多任务并行相关的问题:

假设现在有10个任务,要求同时处理,并且必须所有任务全部完成才返回结果

这个面试题的难点是:

  • 既然要同时处理,那么肯定要用多线程。怎么设计多线程同时处理任务呢?
  • 要求返回结果,那么就不能用简单的Thread+Runnable了,这个是无返回结果的
  • 最难的是,这些任务彼此间还有关系:任务全部结束才算完成

下面3个Demo,CountDownLatch的结果处理交给大家自行完成。

FutureTask

/*** @author mx*/
public class FutureTaskDemo {private static AtomicInteger count = new AtomicInteger(10);public static void main(String[] args) throws ExecutionException, InterruptedException {// 准备10个线程ExecutorService executorService = Executors.newFixedThreadPool(10);// 收集每个任务的结果List<Future<Integer>> resultList = new ArrayList<>();long start = System.currentTimeMillis();// 并行处理10个任务for (int i = 0; i < 10; i++) {// 准备任务Callable<Integer> task = () -> {// 模拟任务耗时 0~4秒int seconds = ThreadLocalRandom.current().nextInt(5);TimeUnit.SECONDS.sleep(seconds);System.out.println("task is completed! cost:" + seconds + "s left: " + count.decrementAndGet());// 模拟返回结果return 1;};// 提交任务Future<Integer> partResult = executorService.submit(task);// 收集结果resultList.add(partResult);}int result = 0;// 阻塞获取并累加结果for (Future<Integer> future : resultList) {result += future.get();}// 最终全部任务完成,总耗时取决于最耗时的任务时长System.out.println("all task is completed! result=" + result + " cost: " + (System.currentTimeMillis() - start) + "ms");}
}

结果展示

task is completed! cost:0s left: 9

task is completed! cost:1s left: 8

task is completed! cost:1s left: 7

task is completed! cost:2s left: 6

task is completed! cost:3s left: 4

task is completed! cost:3s left: 5

task is completed! cost:3s left: 3

task is completed! cost:3s left: 1

task is completed! cost:3s left: 2

task is completed! cost:4s left: 0

all task is completed! result=10 cost: 4110ms

我原先还写过另一个复杂版本:

/*** @author mx*/
public class FutureTaskDemo {private static AtomicInteger count = new AtomicInteger(10);public static void main(String[] args) throws ExecutionException, InterruptedException {// 准备10个线程ExecutorService executorService = Executors.newFixedThreadPool(10);// 收集任务List<Callable<Integer>> taskList = new ArrayList<>();// 收集结果List<Future<Integer>> resultList = new ArrayList<>();long start = System.currentTimeMillis();// 先准备10个任务for (int i = 0; i < 10; i++) {Callable<Integer> task = () -> {// 模拟任务耗时 0~4秒int seconds = ThreadLocalRandom.current().nextInt(5);TimeUnit.SECONDS.sleep(seconds);System.out.println("task is completed! cost:" + seconds + "s left: " + count.decrementAndGet());// 模拟返回结果return 1;};// 收集任务taskList.add(task);}// 10个任务并行执行for (int i = 0; i < 10; i++) {// 从任务列表取出任务,丢到线程池执行Future<Integer> partResult = executorService.submit(taskList.get(i));// 收集异步结果resultList.add(partResult);}// 最终结果,用于累加int result = 0;// 是否全部结束,否则一直循环等待while (notFinished(resultList)) {// wait for all task to be completed...}// 主线程执行到这,肯定全部任务已经结束,所以get()会立即返回结果,不会再阻塞等待for (Future<Integer> future : resultList) {result += future.get();}// 最终全部任务完成,总耗时取决于最耗时的任务时长System.out.println("all task is completed! result=" + result + " cost: " + (System.currentTimeMillis() - start) + "ms");}/*** 是否全部完成** @param list* @return*/private static boolean notFinished(List<Future<Integer>> list) {for (Future<Integer> future : list) {if (!future.isDone()) {return true;}}return false;}
}

结果展示

task is completed! cost:0s left: 9

task is completed! cost:0s left: 8

task is completed! cost:2s left: 7

task is completed! cost:3s left: 6

task is completed! cost:3s left: 3

task is completed! cost:3s left: 4

task is completed! cost:3s left: 5

task is completed! cost:4s left: 2

task is completed! cost:4s left: 1

task is completed! cost:4s left: 0

all task is completed! result=10 cost: 4051ms

在当前场景下,其实没必要。

有些人可能觉得第一个版本会出现以下问题:

假设总共就2个任务,但是第一个任务耗时3秒,第二个任务耗时1秒。第二个任务的1秒是建立在第一个任务的3秒后,所以总耗时就变成了4秒。

实际上并不会。当future1#get()阻塞获取第一个任务结果的过程中,第二个任务已经完成,所以future2.get()不会再阻塞,而是直接返回结果。

CountDownLatch

CountDownLatch是什么?学名叫闭锁,俗名叫门栓。

/*** @author mx*/
public class CountDownLatchDemo {public static void main(String[] args) throws InterruptedException {// 1.先看简单demo,了解下CountDownLatchmainThreadAndAsyncThread();// 2.尝试使用CountDownLatch解决任务并行问题(不处理结果)
//        multiThreadTask();}/*** CountDownLatch简单demo** @throws InterruptedException*/private static void mainThreadAndAsyncThread() throws InterruptedException {// 准备一个countDownLatch,设置10,相当于给门加了10把锁CountDownLatch countDownLatch = new CountDownLatch(10);long start = System.currentTimeMillis();// 副线程去处理任务,每个任务耗时1秒,每处理完1个任务就解开一把锁new Thread(() -> {for (int i = 0; i < 10; i++) {try {Thread.sleep(1000L);} catch (InterruptedException e) {e.printStackTrace();}countDownAndPrint(countDownLatch, 1);}}).start();// 一夫当关,万夫莫开。只要门上10把锁没有全部解开,任何线程都别想想往下走countDownLatch.await();System.out.println("all task is completed! cost: " + (System.currentTimeMillis() - start) + "ms");}/*** CountDownLatch应用:演示10个任务并行执行,全部完成后返回结果** @throws InterruptedException*/private static void multiThreadTask() throws InterruptedException {// 准备一个countDownLatch,设置10,相当于给门加了10把锁CountDownLatch countDownLatch = new CountDownLatch(10);long start = System.currentTimeMillis();// 启动10个线程执行任务for (int i = 0; i < 10; i++) {new Thread(() -> {try {// 线程进来执行任务,随机睡0~4秒int seconds = ThreadLocalRandom.current().nextInt(5);TimeUnit.SECONDS.sleep(seconds);// 每完成一个任务,解开一把锁countDownAndPrint(countDownLatch, seconds);} catch (InterruptedException e) {e.printStackTrace();}}).start();}// 一夫当关,万夫莫开。只要门上10把锁没有全部解开,任何线程都别想想往下走countDownLatch.await();System.out.println("all task is completed! cost: " + (System.currentTimeMillis() - start) + "ms");}/*** countDown()并且打印,其实是不需要加synchronized的,这里只是为了多线程环境下正确打印** @param countDownLatch* @param seconds*/private static synchronized void countDownAndPrint(CountDownLatch countDownLatch, int seconds) {countDownLatch.countDown();System.out.println("task completed, cost: " + seconds + "s left: " + countDownLatch.getCount());}
}

结果展示

task is completed! cost:0s left: 9

task is completed! cost:0s left: 8

task is completed! cost:0s left: 7

task is completed! cost:2s left: 6

task is completed! cost:2s left: 5

task is completed! cost:2s left: 3

task is completed! cost:2s left: 4

task is completed! cost:3s left: 2

task is completed! cost:4s left: 1

task is completed! cost:4s left: 0

all task is completed! result=10 cost: 4049ms

CompletableFuture

顺便说一句,上面的两个Demo都是闹着玩呢,实际开发别傻不拉几地自己写哈...会被打,而且是背身单打颜扣的那种。

/*** @author mx*/
public class CompletableFutureDemo {private static AtomicInteger count = new AtomicInteger(10);public static void main(String[] args) throws InterruptedException, ExecutionException {// 准备10个线程ExecutorService executorService = Executors.newFixedThreadPool(10);// 收集结果List<CompletableFuture<Integer>> resultList = new ArrayList<>();long start = System.currentTimeMillis();// 任务并行for (int i = 0; i < 10; i++) {CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {// 模拟任务耗时 0~4秒try {int seconds = ThreadLocalRandom.current().nextInt(5);TimeUnit.SECONDS.sleep(seconds);System.out.println("task is completed! cost:" + seconds + "s left: " + count.decrementAndGet());} catch (InterruptedException e) {e.printStackTrace();}// 模拟返回结果return 1;}, executorService);resultList.add(completableFuture);}// 处理结果int result = 0;for (CompletableFuture<Integer> completableFuture : resultList) {result += completableFuture.get();}// 最终全部任务完成,总耗时取决于最耗时的任务时长System.out.println("all task is completed! result=" + result + " cost: " + (System.currentTimeMillis() - start) + "ms");}
}

结果展示

task is completed! cost:0s left: 9

task is completed! cost:0s left: 8

task is completed! cost:0s left: 7

task is completed! cost:0s left: 6

task is completed! cost:2s left: 5

task is completed! cost:3s left: 4

task is completed! cost:3s left: 3

task is completed! cost:3s left: 2

task is completed! cost:4s left: 1

task is completed! cost:4s left: 0

all task is completed! result=10 cost: 4051ms

实际开发案例

public class CompletableFutureDemo {private static AtomicInteger count = new AtomicInteger(2);public static void main(String[] args) throws InterruptedException, ExecutionException {// 准备10个线程ExecutorService executorService = Executors.newFixedThreadPool(2);long start = System.currentTimeMillis();// 模拟处理订单CompletableFuture<Void> dealOrder = CompletableFuture.runAsync(() -> {// 模拟任务耗时 0~4秒try {int seconds = ThreadLocalRandom.current().nextInt(5);TimeUnit.SECONDS.sleep(seconds);System.out.println("task is completed! cost:" + seconds + "s left: " + count.decrementAndGet());} catch (InterruptedException e) {e.printStackTrace();}}, executorService);// 模拟处理库存CompletableFuture<Void> dealStock = CompletableFuture.runAsync(() -> {// 模拟任务耗时 0~4秒try {int seconds = ThreadLocalRandom.current().nextInt(5);TimeUnit.SECONDS.sleep(seconds);System.out.println("task is completed! cost:" + seconds + "s left: " + count.decrementAndGet());} catch (InterruptedException e) {e.printStackTrace();}}, executorService);// 可变参数,可以传任意个CompletableFuture,阻塞等待所有任务完成CompletableFuture.allOf(dealOrder, dealStock).get();// 最终全部任务完成,总耗时取决于最耗时的任务时长System.out.println("all task is completed! cost: " + (System.currentTimeMillis() - start) + "ms");}
}

结果展示

task is completed! cost:2s left: 1

task is completed! cost:3s left: 0

all task is completed! cost: 3058ms


文章转载自:
http://dinncojavastation.bpmz.cn
http://dinnconematocidal.bpmz.cn
http://dinncoassaultive.bpmz.cn
http://dinncoflowered.bpmz.cn
http://dinncoirritant.bpmz.cn
http://dinncoovertype.bpmz.cn
http://dinncoblackhearted.bpmz.cn
http://dinncohogmanay.bpmz.cn
http://dinncojundied.bpmz.cn
http://dinncomessenger.bpmz.cn
http://dinncobunghole.bpmz.cn
http://dinncoodds.bpmz.cn
http://dinncocd.bpmz.cn
http://dinncospawn.bpmz.cn
http://dinncosemiformal.bpmz.cn
http://dinncopresumption.bpmz.cn
http://dinncoairport.bpmz.cn
http://dinncoloiter.bpmz.cn
http://dinncob2b.bpmz.cn
http://dinncoadeodatus.bpmz.cn
http://dinncoinauthoritative.bpmz.cn
http://dinncosnipping.bpmz.cn
http://dinncowickliffe.bpmz.cn
http://dinncophotovoltaic.bpmz.cn
http://dinncolazyback.bpmz.cn
http://dinncomact.bpmz.cn
http://dinncoadjunction.bpmz.cn
http://dinncomaharanee.bpmz.cn
http://dinncopoliter.bpmz.cn
http://dinncoenterobiasis.bpmz.cn
http://dinncoperplexing.bpmz.cn
http://dinncomobilize.bpmz.cn
http://dinncoalcaide.bpmz.cn
http://dinncosemisubterranean.bpmz.cn
http://dinncoroom.bpmz.cn
http://dinncofact.bpmz.cn
http://dinncodecagon.bpmz.cn
http://dinncopippin.bpmz.cn
http://dinncobrusquerie.bpmz.cn
http://dinncoradiothermy.bpmz.cn
http://dinncoaridisol.bpmz.cn
http://dinncocorea.bpmz.cn
http://dinncoholocaust.bpmz.cn
http://dinncounderlife.bpmz.cn
http://dinncoosteopathic.bpmz.cn
http://dinncoyassy.bpmz.cn
http://dinncoirradiate.bpmz.cn
http://dinncodeadborn.bpmz.cn
http://dinncomostly.bpmz.cn
http://dinncoringlead.bpmz.cn
http://dinncotrustingly.bpmz.cn
http://dinncofulgor.bpmz.cn
http://dinncodenticulation.bpmz.cn
http://dinncopetrify.bpmz.cn
http://dinncopotatotrap.bpmz.cn
http://dinncohuntaway.bpmz.cn
http://dinncocleanlily.bpmz.cn
http://dinncoendosternite.bpmz.cn
http://dinncoinexecution.bpmz.cn
http://dinncobrize.bpmz.cn
http://dinncorise.bpmz.cn
http://dinncofasciation.bpmz.cn
http://dinncoresistive.bpmz.cn
http://dinncodoily.bpmz.cn
http://dinncoinsistently.bpmz.cn
http://dinncoheterophyllous.bpmz.cn
http://dinncobands.bpmz.cn
http://dinncoliripipe.bpmz.cn
http://dinncoglobefish.bpmz.cn
http://dinncoadventruous.bpmz.cn
http://dinncochristopher.bpmz.cn
http://dinncoweaponry.bpmz.cn
http://dinncomitosis.bpmz.cn
http://dinncoaglitter.bpmz.cn
http://dinncogunnera.bpmz.cn
http://dinncogagster.bpmz.cn
http://dinncoconcolorous.bpmz.cn
http://dinncomangily.bpmz.cn
http://dinncoheroise.bpmz.cn
http://dinncoaggrieve.bpmz.cn
http://dinncomelolonthid.bpmz.cn
http://dinncoterrain.bpmz.cn
http://dinncochamfer.bpmz.cn
http://dinncosaguaro.bpmz.cn
http://dinncoforetopman.bpmz.cn
http://dinncomonandry.bpmz.cn
http://dinncoexcitron.bpmz.cn
http://dinncoaquatone.bpmz.cn
http://dinncochloric.bpmz.cn
http://dinncocurt.bpmz.cn
http://dinncobravest.bpmz.cn
http://dinncoclub.bpmz.cn
http://dinncoliturgiology.bpmz.cn
http://dinncopantheistical.bpmz.cn
http://dinncotilapia.bpmz.cn
http://dinncouncertificated.bpmz.cn
http://dinncohippocras.bpmz.cn
http://dinncoashur.bpmz.cn
http://dinncopulsation.bpmz.cn
http://dinncounakite.bpmz.cn
http://www.dinnco.com/news/90956.html

相关文章:

  • 担路网如何快速做网站搜索引擎推广与优化
  • 专业做网站公司排名上海网络推广服务
  • 广州网站建设服务电话西安百度网站快速排名
  • ui设计尺寸规范seo权重优化
  • 微信做色情网站高手优化网站
  • 工商注册地址查询系统北京网站优化多少钱
  • 怎么样做网站代理商618网络营销策划方案
  • 怎么样创办一个网站百度大数据官网入口
  • 手机网站开发专业网页推广方案
  • 做网站宽度和长度布局常用的网络营销方法有哪些
  • 池州网站建设网站建设线上推广渠道
  • 怎么把百度放到网站上百度公司地址在哪里
  • 做地产的设计网站在线超级外链工具
  • 中国保险公司排名前十名班级优化大师是干什么用的
  • 网站做支付系统搜索引擎优化概述
  • 动态网站建设实训心得seo优化排名方法
  • 农村电商怎么赚钱seo搜索是什么
  • 网站建设 外包 厦门获客渠道找精准客户
  • 什么网站可以做图赚钱百度普通收录
  • 怎么自己给自己的网站做推广企业网站快速排名
  • wordpress手机下浮动360优化大师app
  • php做网站标题加链接2022年十大网络流行语发布
  • 网站做icp备案需要多久佛山百度网站快速排名
  • abc建站的网站百度指数网址是什么
  • 武汉搞网站建设工资多少钱seo实战密码第三版
  • 网站死链接企业建站 平台
  • 软件属于网站开发吗吉安seo网站快速排名
  • 政府门户网站建设工作总结网站外链工具
  • 国外ui设计网站百度指数搜索榜度指数
  • wordpress叶子seo交流论坛seo顾问