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

  • 相关阅读:
    Hibernate 事务和并发控制
    InfoSYS-20170114
    STM32学习笔记:读写内部Flash(介绍+附代码)
    STM32串口通信配置(USART1+USART2+USART3+UART4)
    Keil-MDK编译完成后代码大小
    STM32窗口看门狗和独立看门狗的区别,看门狗介绍及代码演示
    关于单片机编程里面调用sprintf死机的解决方法及原因分析
    ESP8266 wifi 模块配置,Wechat+APP控制实现
    STM32常见问题
    深入浅出 TCP/IP 协议
  • 原文地址:https://www.cnblogs.com/ctaixw/p/12977818.html
Copyright © 2011-2022 走看看