• 使用Callable、Future以及FutureTask进行线程操作


    Future接口代表异步计算的结果,并且提供方法来检测异步过程的进展。Callable接口与Runnable接口比较类似,提供线程的执行体,即run方法的内容。

    Future与Callable结合使用开启一个新线程执行,最大的特点是能提供返回值,这样也就能实现类似同步执行的情况,看以下示例,在新线程中模拟5s的耗时操作,使用future.get将阻塞等待返回结果。

    package demo.thread;
    
    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 CallableDemo {
        public static void main(String[] args) throws InterruptedException,
                ExecutionException {
            ExecutorService executorService = Executors.newCachedThreadPool();
            Future<String> future = executorService.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    Thread.sleep(5000);
                    return "future result";
                }
            });
            System.out.println(System.currentTimeMillis());
            System.out.println(future.get());
            System.out.println(System.currentTimeMillis());
        }
    
    }

    执行结果如下:

    1562077654406
    future result
    1562077659407

    FutureTask间接实现了Runnable和Future接口,同样可以实现上述功能,如下:

    package demo.thread;
    
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.FutureTask;
    
    public class FutureTaskDemo {
    
        public static void main(String[] args) throws InterruptedException,
                ExecutionException {
            FutureTask<String> futureTask = new FutureTask<String>(
                    new Callable<String>() {
    
                        @Override
                        public String call() throws Exception {
                            Thread.sleep(5000);
                            return "future result";
                        }
                    });
            new Thread(futureTask).start();
            System.out.println(System.currentTimeMillis());
            System.out.println(futureTask.get());
            System.out.println(System.currentTimeMillis());
    
        }
    
    }

    执行结果如下:

    1562077797983
    future result
    1562077802985

     

  • 相关阅读:
    将Mat类型坐标数据生成pts文件
    DelaunayTriangulation_VoronoiDiagram_using_OpenCV的实现
    安装python第三方库
    安装wordcloud第三方库Unable to find vcvarsall.bat
    Vec3b类型数据确定颜色通道
    使用Inno Setup Compiler制作安装软件包
    QT-This application failed to start because it could not find or load the Qt platform plugin "windows"
    m函数与m文件的命名
    当前目录如何打开cmd
    [Machine Learning & Algorithm] 随机森林(Random Forest)-转载
  • 原文地址:https://www.cnblogs.com/silenceshining/p/11123496.html
Copyright © 2020-2023  润新知