| 名称 | 类型 | 特点 |
|---|---|---|
| Thread | class | 单继承 ,无返回值 |
| Runnalble | interface | 多实现,无返回值 |
| Callable | interface | 多实现,有返回值,带泛型,可抛出异常,Callable⼀般是配合线程池⼯具Executors来使⽤的 |
| Future | interface | 多实现,有返回值,带泛型,可取消(cancel方法) |
| FuturTask | class | 多实现,有返回值,实现的RunnableFuture接⼝,⽽RunnableFuture接⼝同时继承了Runnable 接⼝和Future接⼝ |
JDK提供了 Thread 类和 Runnalble 接⼝来让我们 实现⾃⼰的线程类。
- 继承 Thread 类,并重写 run ⽅法
- 实现 Runnable 接⼝的 run ⽅法
Thread类继承关系图:
其实Thread也是实现了Runable接口。继承Thread类,Java代码实现:
//调⽤ start() 线程启动!
public class Demo {
public static class MyThread extends Thread {
@Override
public void run() {
System.out.println("MyThread");
}
}
public static void main(String[] args) {
Thread myThread = new MyThread();
myThread.start();
}
}
Runable继承关系图:
实现Runnable接⼝,Java代码实现:
public class Demo {
public static class MyThread implements Runnable {
@Override
public void run() {
System.out.println("MyThread");
}
}
public static void main(String[] args) {
new MyThread().start();
// Java 8 函数式编程,可以省略MyThread类
new Thread(() -> {
System.out.println("Java 8 匿名内部类");
}).start();
}
}
Thread类与Runnable接⼝的⽐较:
- 由于Java单继承,多实现的特性,Runnable接⼝使⽤起来⽐Thread更灵活
- Runnable接⼝出现更符合⾯向对象,将线程单独进⾏对象的封装
- Runnable接⼝出现降低了线程对象和线程任务的耦合性。 如果使⽤线程时不需要使⽤Thread类的诸多⽅法,显然使⽤Runnable接⼝更为轻量
Callable接⼝
// ⾃定义Callable class Task implements CallableFuture与FutureTask{ @Override public Integer call() throws Exception { // 模拟计算需要⼀秒 Thread.sleep(1000); return 2; } public static void main(String args[]){ // 使⽤ ExecutorService executor = Executors.newCachedThreadPool(); Task task = new Task(); Future result = executor.submit(task); // 注意调⽤get⽅法会阻塞当前线程,直到得到结果。 // 所以实际编码中建议使⽤可以设置超时时间的重载get⽅法。 System.out.println(result.get()); } }
Future接⼝部分方法:
public abstract interface Future{ //试图取消一个线程 public abstract boolean cancel(boolean paramBoolean); //线程是否已经取消 public abstract boolean isCancelled(); //线程是否已经执行完成 public abstract boolean isDone(); //获取执行结果(阻塞) public abstract V get() throws InterruptedException, ExecutionException; //获取执行结果(阻塞最大时间毫秒数) public abstract V get(long paramLong, TimeUnit paramTimeUnit) throws InterruptedException, ExecutionException, TimeoutException; }
FuturTask类实现的RunnableFuture接⼝,⽽RunnableFuture接⼝同时继承了Runnable接⼝和Future接⼝



