1 Star 0 Fork 2

Emotion404 / JavaBooks

forked from 帝八哥 / JavaBooks 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
线程的创建方式.md 1.79 KB
一键复制 编辑 原始数据 按行查看 历史
DreamCats 提交于 2020-08-11 13:43 . 线程的创建方式

面试官:线程的创建方式有哪些?

我:我目前知道4种:分别如下:

Thread

​```java
public class Test extents Thread {
    public void run() {
      // 重写Thread的run方法
      System.out.println("dream");
    }
    
    public static void main(String[] args) {
        new Test().start();
    }
}
​```

Runnable

​```java
public class Test {
    public static void main(String[] args) {
        new Thread(() -> {
            System.out.println("dream");
        }).start();
    } 
}
​```

Callable

public class Test {
    public static void main(String[] args) {
        // FutureTask 构造方法包装了Callable和Runnable。
        FutureTask<Integer> task = new FutureTask<>(() -> {
            System.out.println("dream");
            return 0;
        });
        new Thread(task).start();
    }
}
​```

线程池

​```java
public class Test {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(1);
        threadPool.submit(() -> {
            System.out.println("dream");
        });
        threadPool.shutdown();
    }
}

面试官:Runnable和Callable有啥区别?

我:那得先看源码咯

请看

@FunctionalInterface
public interface Runnable {
   /**
    * 被线程执行,没有返回值也无法抛出异常
    */
    public abstract void run();
}

@FunctionalInterface
public interface Callable<V> {
    /**
     * 计算结果,或在无法这样做时抛出异常。
     * @return 计算得出的结果
     * @throws 如果无法计算结果,则抛出异常
     */
    V call() throws Exception;
}
  1. Runnable没有返回值并且无法抛出异常
  2. 不巧,我Callable可以做到你不能做到的

线程池的源码后边讲

马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/Emotion404/JavaBooks.git
git@gitee.com:Emotion404/JavaBooks.git
Emotion404
JavaBooks
JavaBooks
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891