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();
            }
        }
    }
    复制代码
     
    from: https://www.cnblogs.com/liujinhong/p/6510667.html
  • 相关阅读:
    perimeter of squares
    map
    django路由
    for的骚用法
    3和5的倍数相加和
    PeteCake 字典和最小值
    Find the missing letter
    实现简单的ssh功能
    开源运维工具体系
    vsftp在iptables中的配置
  • 原文地址:https://www.cnblogs.com/GarfieldEr007/p/10166046.html
Copyright © 2011-2022 走看看