• 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
  • 相关阅读:
    第一部分:开发前的准备-第二章 基础入门
    多线程笔记
    .net平台下垃圾回收机制
    xml基本操作和保存配置文件应用实例
    .net平台下C#socket通信(中)
    .net平台下C#socket通信(上)
    泛型
    面向过程和面向对象及面向对象的三大特征
    值类型和引用类型及参数传递
    js中typeof与instanceof区别
  • 原文地址:https://www.cnblogs.com/xinyuyu/p/3706508.html
Copyright © 2020-2023  润新知