创建线程的三种方式
1. 继承Thread类,重写run方法
| public class MyThread extends Thread { |
| public void run() { |
| System.out.println("Hello from MyThread!"); |
| } |
| } |
| |
| public class Main { |
| public static void main(String[] args) { |
| MyThread thread = new MyThread(); |
| thread.start(); |
| } |
| } |
| |
| |
| Hello from MyThread! |
2. 实现Runnable接口,实现run方法
| public class MyRunnable implements Runnable { |
| public void run() { |
| System.out.println("Hello from MyRunnable!"); |
| } |
| } |
| |
| public class Main { |
| public static void main(String[] args) { |
| Thread thread = new Thread(new MyRunnable()); |
| thread.start(); |
| } |
| } |
| |
| |
| Hello from MyRunnable! |
2. 使用Callable和Future创建有返回值的线程
| import java.util.concurrent.Callable; |
| import java.util.concurrent.Future; |
| import java.util.concurrent.FutureTask; |
| |
| public class MyCallable implements Callable<String> { |
| public String call() { |
| return "Hello from MyCallable!"; |
| } |
| } |
| |
| public class Main { |
| public static void main(String[] args) throws Exception { |
| Callable<String> callable = new MyCallable(); |
| FutureTask<String> futureTask = new FutureTask<>(callable); |
| Thread thread = new Thread(futureTask); |
| thread.start(); |
| String result = futureTask.get(); |
| System.out.println(result); |
| } |
| } |
| |
| |
| Hello from MyCallable! |
以上是Java创建线程的三种方式,分别使用了
- 继承Thread类、
- 实现Runnable接口、
- 使用Callable和Future创建有返回值的线程。
通过这三种方式,我们可以灵活地创建多线程应用程序。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署