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(); } } }