多线程之Runnable和Callable的区别

借鉴:

https://blog.csdn.net/mryang125/article/details/81878168

 

多线程理解:

https://www.cnblogs.com/jmsjh/p/7762034.html

 

package com.company;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class Main {

    public static void main(String[] args) throws InterruptedException {
     // 线程池 ThreadPoolExecutor executor
= new ThreadPoolExecutor(5, 10, 300L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(20000)); // 控制返回的数据按照执行顺序加载打印 List<Future> futureList = new ArrayList<>(); int count = 15; // 控制线程全部执行完成 CountDownLatch downLatch = new CountDownLatch(count);
for (int i = 0; i < count; i++) { int finalI = i; Future<String> submit = executor.submit(()->get(finalI)); futureList.add(submit); downLatch.countDown(); } downLatch.await();
    // 获取线程执行结果 可以单独拿出来作为一个方法
for (Future future : futureList) { if (future != null) { try { String result = (String) future.get(200L, TimeUnit.MILLISECONDS); System.out.println(result); } catch (ExecutionException | TimeoutException e) { // 超时和线程失败策略 e.printStackTrace(); } } }
// 项目中不需要此步骤 测试代码需要 executor.shutdown(); } public static String get(int i) { return i + ",正在执行"; } }

 

posted @ 2020-11-13 15:26  土木转行的人才  阅读(103)  评论(0编辑  收藏  举报