zoukankan      html  css  js  c++  java
  • 使用多线程 执行有返回值的方法

    public class ThreadTest {

    private static BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(50000);
    public static ThreadPoolExecutor executor;

    static {
    executor = new ThreadPoolExecutor(15, 100, 60L,
    TimeUnit.SECONDS, queue, new ThreadPoolExecutor.AbortPolicy());
    }

    public static void main(String[] args) {

    List<Future> futureList = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
    final int a = i;
    Future futureString = executor.submit((Callable<Object>)() -> handle(a));
    futureList.add(futureString);
    }

    int sum = 0;
    for (Future future : futureList) {
    Integer returnint = (Integer)getFutureObject(future);
    System.out.println(returnint +" " + new Date());
    sum = sum + returnint;
    }
    System.out.println(sum);
    }

    public static int handle(int num) {
    int sleepNUM = 10 - num;

    System.out.println("num strart " + num +" "+ new Date());
    try {
    Thread.sleep(sleepNUM * 1000);
    }catch (Exception e){}
    System.out.println("num end " + num +" " + new Date() );

    return num;

    }

    private static Object getFutureObject(Future future){
    try {
    return future.get(600, TimeUnit.SECONDS);
    }catch (Exception ex){
    }
    return null;
    }
    }

    ---------------------------

    num strart 3 Thu May 28 01:55:02 CST 2020
    num strart 6 Thu May 28 01:55:02 CST 2020
    num strart 1 Thu May 28 01:55:02 CST 2020
    num strart 8 Thu May 28 01:55:02 CST 2020
    num strart 4 Thu May 28 01:55:02 CST 2020
    num strart 0 Thu May 28 01:55:02 CST 2020
    num strart 2 Thu May 28 01:55:02 CST 2020
    num strart 5 Thu May 28 01:55:02 CST 2020
    num strart 7 Thu May 28 01:55:02 CST 2020
    num strart 9 Thu May 28 01:55:02 CST 2020
    num end 9 Thu May 28 01:55:03 CST 2020
    num end 8 Thu May 28 01:55:04 CST 2020
    num end 7 Thu May 28 01:55:05 CST 2020
    num end 6 Thu May 28 01:55:06 CST 2020
    num end 5 Thu May 28 01:55:07 CST 2020
    num end 4 Thu May 28 01:55:08 CST 2020
    num end 3 Thu May 28 01:55:09 CST 2020
    num end 2 Thu May 28 01:55:10 CST 2020
    num end 1 Thu May 28 01:55:11 CST 2020
    num end 0 Thu May 28 01:55:12 CST 2020
    0 Thu May 28 01:55:12 CST 2020
    1 Thu May 28 01:55:12 CST 2020
    2 Thu May 28 01:55:12 CST 2020
    3 Thu May 28 01:55:12 CST 2020
    4 Thu May 28 01:55:12 CST 2020
    5 Thu May 28 01:55:12 CST 2020
    6 Thu May 28 01:55:12 CST 2020
    7 Thu May 28 01:55:12 CST 2020
    8 Thu May 28 01:55:12 CST 2020
    9 Thu May 28 01:55:12 CST 2020
    45

  • 相关阅读:
    解决IDEA中项目出现cannot resolve method ‘XXXXX(java.lang.String)’问题
    JDK1.8下载、安装和环境配置教程
    JavaBean是什么,POJO是什么
    什么是MVC
    IDEA使用-test下没有resource文件
    Hive入门--3.UDF编写与使用
    Hive入门--2.分区表 外部分区表 关联查询
    Hive入门--1.简介与环境搭建
    SLF4J-jar包多绑定冲突解决
    Hbase--1 简介
  • 原文地址:https://www.cnblogs.com/ctaixw/p/12977818.html
Copyright © 2011-2022 走看看