我们常用的创建线程方式一般有下面 3 种:
- 继承Thread,重写run方法。
- 实现Runnable接口,重新run方法。
- 实现 Callable 接口并重写call方法。
Callable 与 Runnable 相比有以下 2 点不同:
- Callable 可以在任务结束的时候提供一个返回值,Runnable 无法提供这个功能
- Callable 的 call 方法分可以抛出异常,而 Runnable 的 run 方法不能抛出异常。
public class ThreadTest {
public static void main(String[] args) {
System.out.println("main start");
ExecutorService threadPool = Executors.newSingleThreadExecutor();
// Future<?> future = threadPool.submit(new MyRunnable()) ;
Future<String> future = threadPool.submit(new MyCallable());
try {
// 这里会发生阻塞
System.out.println(future.get());
} catch (Exception e) {
} finally {
threadPool.shutdown();
}
System.out.println("main end");
}
}
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
// 模拟耗时任务
Thread.sleep(3000);
System.out.println("MyCallable 线程:" + Thread.currentThread().getName());
return "MyCallable" ;
}
}
public class MyRunnable implements Runnable {
@Override
public void run() {
// 模拟耗时任务
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("MyRunnable");
}
}