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

    通过实现callable的call方法可以完成线程的操作,并且返回一个需要的值

    package test1;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    public class TaskWithResult implements Callable<String> {
        
        // 实现call方法,在方法中输出两句话
        public String call() throws Exception {
            //Thread.sleep(time);
            System.out.println(Thread.currentThread().getName() + "run...");
            Thread.sleep(100);
            System.out.println(Thread.currentThread().getName() + "test...");
            // 返回一个字符串
            return Thread.currentThread().getName() + " has executed";
        }
        
        
        
        
        public static void main(String[] args) throws InterruptedException, ExecutionException {
            // 用Executors来管理线程
            ExecutorService exec = Executors.newCachedThreadPool();
            // 用Future来接受返回值
            List<Future<String>> results = new ArrayList<Future<String>>();
            for(int i=0; i<=10; i++){
                // 将返回值放入Future<String>类型的List中去
                results.add(exec.submit(new TaskWithResult()));
            }
            // 得到返回值
            //System.out.println(results.get(0).get());
            exec.shutdown();
        }
    }

    输出结果

    pool-1-thread-1run...
    pool-1-thread-2run...
    pool-1-thread-3run...
    pool-1-thread-4run...
    pool-1-thread-5run...
    pool-1-thread-7run...
    pool-1-thread-8run...
    pool-1-thread-9run...
    pool-1-thread-11run...
    pool-1-thread-6run...
    pool-1-thread-10run...
    pool-1-thread-2test...
    pool-1-thread-1test...
    pool-1-thread-4test...
    pool-1-thread-3test...
    pool-1-thread-9test...
    pool-1-thread-8test...
    pool-1-thread-7test...
    pool-1-thread-5test...
    pool-1-thread-10test...
    pool-1-thread-6test...
    pool-1-thread-11test...

    看出来程序不是顺序运行的,而是将每一个线程分时运行。

    可以通过Future的get()来得到返回值

    pool-1-thread-1test...
    pool-1-thread-1 has executed
    pool-1-thread-3test...
    pool
  • 相关阅读:
    【NOIP2017】跳房子
    MySQL的多表查询(笛卡尔积原理)
    MySQL的delete误操作的快速恢复方法
    MYSQL高可用集群架构-MHA架构
    mysql数据库的创建问题
    Python中xlrd和xlwt模块使用方法----》》数据库数据导出(之一)
    mysql数据库的批量数据导入与导出,性能提升。
    使用Python对ElasticSearch获取数据及操作
    SQL语句
    ElasticSearch-排序
  • 原文地址:https://www.cnblogs.com/xinyuyu/p/3706508.html
Copyright © 2011-2022 走看看