Java创建线程的方式
Java创建线程的方式
- Java创建线程的方式一共有三种:
- 继承Thread类
- 实现Runnable接口
- 使用Executor框架
- 使用Callable和Future接口
- 其中,继承Thread类和实现Runnable接口都需要重写run()方法。
1. 继承Thread类
- 继承Thread类是创建线程的最简单方式。通过继承Thread类并重写其run()方法来定义线程的任务。
1 | class MyThread extends Thread { |
2. 实现Runnable接口
- 实现Runnable接口是另一种常用的创建线程的方式。通过实现Runnable接口并重写其run()方法来定义线程的任务。
1 | class MyRunnable implements Runnable { |
3. 使用Executor框架
- 通过Executor可以将任务提交给线程池,由线程池来管理线程的生命周期和执行
1 | import java.util.concurrent.Executor; |
4. 使用Callable和Future接口
- 实现Callable接口可以创建可以返回结果的线程任务。与Runnable不同,Callable的call()方法可以返回一个值,并且可以抛出异常。
1 | import java.util.concurrent.Callable; |
