zoukankan      html  css  js  c++  java
  • Java线程之FutureTask

    简述

    FutureTask是Future接口的实现类,并提供了可取消的异步处理的功能,它包含了启动和取消(start and cancel)任务的方法,同时也包含了可以返回FutureTask状态(completed or cancelled)的方法。我们可以自定义一个Future任务,然后使用线程池执行器Java Thread Pool Executor 去异步执行任务。

    FutureTask

    在这里插入图片描述

    从类图中可以看出,FutureTask实现了接口RunnableFuture,接口RunnableFuture又继承了Runnable和Future接口,所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的结果,因此FutureTask提供了两个构造方法:

    public FutureTask(Callable<V> callable)
    public FutureTask(Runnable runnable, V result)
    

    使用事例

    1.使用Callable+Future获取执行结果

    package com.lkf.mulithread;
    
    import java.util.concurrent.*;
    
    public class CallableFutureExample {
        public static void main(String[] args) {
            //创建线程池
            ExecutorService executor = Executors.newCachedThreadPool();
            //实例化任务
            MyTask task = new MyTask();
            //提交任务
            Future<Integer> result = executor.submit(task);
            //关闭线程池
            executor.shutdown();
    
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
    
            System.out.println("主线程在执行任务");
    
            try {
                System.out.println("MyTask的返回值:"+result.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
    
            System.out.println("所有任务执行完毕");
        }
    
        static class MyTask implements Callable<Integer> {
            @Override
            public Integer call() throws Exception {
                System.out.println("子线程正在执行");
                Thread.sleep(5000);
                return 1000;
            }
        }
    }
    
    

    2.使用Callable+FutureTask获取执行结果

    package com.lkf.mulithread;
    
    import java.util.concurrent.*;
    
    public class FutureTaskExample {
        public static 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 Thread.currentThread().getName();
            }
    
        }
    
        public static void main(String[] args) {
            MyCallable callable1 = new MyCallable(1000);
            MyCallable callable2 = new MyCallable(2000);
    
            FutureTask<String> futureTask1 = new FutureTask<String>(callable1);
            FutureTask<String> futureTask2 = new FutureTask<String>(callable2);
    
            ExecutorService executor = Executors.newFixedThreadPool(2);
            executor.execute(futureTask1);
            executor.execute(futureTask2);
    
            while (true) {
                try {
                    if(futureTask1.isDone() && futureTask2.isDone()){
                        System.out.println("Done");
                        //shut down executor service
                        executor.shutdown();
                        return;
                    }
    
                    if(!futureTask1.isDone()){
                        //wait indefinitely for future task to complete
                        System.out.println("FutureTask1 output="+futureTask1.get());
                    }
    
                    System.out.println("Waiting for FutureTask2 to complete");
                    String s = futureTask2.get(200L, TimeUnit.MILLISECONDS);
                    if(s !=null){
                        System.out.println("FutureTask2 output="+s);
                    }
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }catch(TimeoutException e){
                    //do nothing
                }
            }
    
        }
    
    }
    
    

    输出结果:

    FutureTask1 output=pool-1-thread-1
    Waiting for FutureTask2 to complete
    Waiting for FutureTask2 to complete
    Waiting for FutureTask2 to complete
    Waiting for FutureTask2 to complete
    Waiting for FutureTask2 to complete
    FutureTask2 output=pool-1-thread-2
    Done
    
  • 相关阅读:
    Linux tcpdump命令详解
    移动开发网站收集
    Struts+2权威指南基于WebWork核心的MVC开发源码下载
    Eclipse+php插件+Xdebug搭建PHP完美开发/调试环境指南
    java相对目录和绝对目录解析
    python学习网站搜集
    window下开发iphone程序环境搭建iphone tool chain
    Windows下编译objectiveC
    java class路径获取
    完全优化MySQL数据库性能的八个方法
  • 原文地址:https://www.cnblogs.com/liukaifeng/p/10052649.html
Copyright © 2011-2022 走看看