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

    1. 创建线程的三种方式:

    • 继承Thread,重写run方法
    • 实现Runnable接口,重新run方法
    • 实现Callable接口,重写call方法

    2. Callable接口实际上是属于Executor框架中的功能类,Callable接口与Runnable接口的功能类似,但提供了比Runnable更加强大的功能。

    • Callable可以在任务结束的时候提供一个返回值,Runnable无法提供这个功能
    • Callable的call方法分可以抛出异常,而Runnable的run方法不能抛出异常。

    3. 实例

    复制代码
    package thread.learn;
    
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    /**
     * Created by liujinhong on 2017/3/6.
     */
    public class CallableAndFuture {
        static class MyThread implements Callable<String> {
            @Override
            public String call() throws Exception {
                return "Hello world";
            }
        }
    
        static class MyThread2 implements Runnable {
            @Override
            public void run() {
    
            }
        }
    
        public static void main(String[] args) {
            ExecutorService threadPool = Executors.newSingleThreadExecutor();
            Future<String> future = threadPool.submit(new MyThread());
    
            try {
                System.out.println(future.get());
            } catch (Exception e) {
    
            } finally {
                threadPool.shutdown();
            }
        }
    }
    复制代码

     

  • 相关阅读:
    Ubuntu环境下IPython的搭建和使用
    智能移动导游解决方案简介
    企业文化、团队文化与知识共享
    CoinPunk项目介绍
    Insight API开源项目介绍
    比特币Bitcoin源代码安装编译
    Javascript单元测试Unit Testing之QUnit
    Node.js的UnitTest单元测试
    Node.js调试
    Alfresco 4 项目介绍
  • 原文地址:https://www.cnblogs.com/pypua/p/10207495.html
Copyright © 2011-2022 走看看