zoukankan      html  css  js  c++  java
  • FutureTask的使用

    package org.zln.thread.pool.ft;

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;

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

    /**
    * Created by sherry on 17/1/6.
    */
    public class Demo01 {

    /**
    * 日志
    */
    private static Logger logger = LoggerFactory.getLogger(Demo01.class);

    public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {

    ExecutorService executor = Executors.newFixedThreadPool(10); // 创建线程池并返回ExecutorService实例

    List<FutureTask<String>> list = new ArrayList<>();

    //异步添加任务
    for (int i = 0; i < 10; i++) {
    MyCallable callable = new MyCallable(1000); // 要执行的任务
    FutureTask<String> futureTask = new FutureTask<String>(callable);
    executor.submit(futureTask);
    logger.debug("添加"+i);
    list.add(futureTask);
    }

    //顺序打印执行结果
    for (FutureTask<String> futureTask:list){
    logger.debug(futureTask.get());
    }


    executor.shutdown();

    }
    }

    /**
    * 线程任务类
    */
    class MyCallable implements Callable<String> {
    private long waitTime;

    public MyCallable(int timeInMillis) {
    this.waitTime = timeInMillis;
    }

    @Override
    public String call() throws Exception {
    Thread.sleep(waitTime);
    //return the thread name executing this callable task
    return Thread.currentThread().getName();
    }

    }




    解决的问题:线程池内线程的超时控制;异步调用;集中返回线程处理结果
  • 相关阅读:
    AS400一些有用的命令
    Publish的时候某些需要用到的文件没deploy上去
    DB2一些SQL的用法
    根据PostgreSQL 系统表查出字段描述
    linux memcached 安装
    CentOS下XEN虚拟服务器安装配置
    Apache the requested operation has failed
    PHP配置兼容ZendDebugger和Optimizer
    虚拟机比较
    memcache 运行情况,内存使用
  • 原文地址:https://www.cnblogs.com/sherrykid/p/6255037.html
Copyright © 2011-2022 走看看