美文网首页
线程/Runnable/Callable之间的关系

线程/Runnable/Callable之间的关系

作者: 叫我C30混凝土 | 来源:发表于2020-08-17 22:33 被阅读0次
  • 只有Thread代表线程,那么Runnable呢?
    • Runnable代表一个[任务];
    • 可以被任何一个线程执行;
public static void main(String[] args) throws InterruptedException {
        //创建线程的方法:方法一
        //构造函数java.lang.Thread#Thread(java.lang.Runnable)
        // Runnable只是一个任务,交给哪个线程执行都可以
        new Thread(() -> {
            try {
                Thread.sleep(6000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        //创建线程的方法:方法二
        //构造函数java.lang.Thread#Thread(),创建了匿名内部类,覆盖了Thread.run()方法;
        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(6000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

ps:Thread 实现了 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.
     *
     * 当一个类实现Runnable接口取创建线程,启动该线程会导致在该单独执行的线程中调   
     * 用对象的run方法.
     * 一般run方法可以采取任何操作;
     */
java.lang.Runnable#run 注释
线程池/线程的关系:
因为线程的创建非常昂贵,而线程池可以提前进行储备,当任务需要执行时,直接使用线程池中的线程即可;

java.util.concurrent.ExecutorService#submit(java.lang.Runnable)
在线程池中提前储备一个任务,这个任务未来被谁执行,如何执行都不需要关注;

具体实现类,例子:
java.util.concurrent.Executors#newCachedThreadPool()
java.util.concurrent.Executors#newSingleThreadScheduledExecutor()
  • 什么是Callable?
    • Runnable的限制
      • 不能返回值;
      • 不能抛出checked exception;
  • Callable解决了这些限制问题;
Runnable和Callable没有本质的区别,都是一个抽象的[任务],与线程没有关系,一个线程可以选择执行这些任务;区别如上;

相关文章

网友评论

      本文标题:线程/Runnable/Callable之间的关系

      本文链接:https://www.haomeiwen.com/subject/xjecjktx.html