• 技术文章 >java >java基础

    Java runnable和callable的异同

    小妮浅浅小妮浅浅2021-04-28 17:18:09原创4009

    1、相同点

    两者都是接口

    两者都需要调用Thread.start启动线程

    2、不同点

    callable的核心是call()方法,允许返回值,runnable的核心是run()方法,没有返回值

    call()方法可以抛出异常,但是run()方法不行

    callable和runnable都可以应用于executors,thread类只支持runnable

    3、实例

    Runnable和Callable的接口定义

    @FunctionalInterface
    public interface Runnable {
        /**
         * When an object implementing interface <code>Runnable</code> is used
         * to create a thread, starting the thread causes the object's
         * <code>run</code> method to be called in that separately executing
         * thread.
         * <p>
         * The general contract of the method <code>run</code> is that it may
         * take any action whatsoever.
         *
         * @see     java.lang.Thread#run()
         */
        public abstract void run();
    }
    @FunctionalInterface
    public interface Callable<V> {
        /**
         * Computes a result, or throws an exception if unable to do so.
         *
         * @return computed result
         * @throws Exception if unable to compute a result
         */
        V call() throws Exception;
    }

    以上就是Java runnable和callable的异同,希望对大家有所帮助。更多Java学习指路:Java基础

    专题推荐:java runnable callable
    品易云
    上一篇:Java Executors中的四种线程池 下一篇:java sleep()和wait()的区别

    相关文章推荐

    • java ThreadLocal的创建和访问• java如何在表格添加水印• java类加载器的常用方法• java如何重写findClass方法• java中&和&&有什么区别• JavaScript数组有哪些遍历方法• JavaScript for-in和for-of的不同点• JavaScript使用map创建新数组• filter在JavaScript中过滤数组元素• Java序列化是什么• Java反序列化如何理解• java单例中的饱汉模式实现• java单例中饿汉模式的使用• java懒汉和饿汉模式的区别• java单例模式中的Holder是什么• java枚举类型的原理• java静态方法和非静态方法的介绍• java io和nio的区别

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网