Java中创建线程的几种方式
盘点一下Java中创建线程的几种方式
一、继承Thread类,重写run()方法
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class MyThread extends Thread { @Override public void run() { System.out.println( "my thread start " + Thread.currentThread().getName()); } public static void main(String[] args) { System.out.println( "main thread start " +Thread.currentThread().getName()); MyThread myThread = new MyThread(); myThread.start(); } } |
二、实现Runnable接口,并重写run()方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class MyThreadRunnable implements Runnable { @Override public void run() { System.out.println( "my thread start " + Thread.currentThread().getName()); } public static void main(String[] args) { System.out.println( "main thread start " + Thread.currentThread().getName()); MyThreadRunnable myThreadRunnable = new MyThreadRunnable(); Thread thread = new Thread(myThreadRunnable); thread.start(); } } |
三、实现Callable接口,并重写call()方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public class MyThreadCallable implements Callable<Integer> { @Override public Integer call() throws Exception { System.out.println( "my thread start " + Thread.currentThread().getName()); Integer ret = 0 ; for ( int i = 0 ; i < 10 ; i++) { ret += i; } return ret; } public static void main(String[] args) throws ExecutionException, InterruptedException { MyThreadCallable myThreadCallable = new MyThreadCallable(); FutureTask<Integer> futureTask = new FutureTask<>(myThreadCallable); Thread thread = new Thread(futureTask, "A" ); thread.start(); int ret = futureTask.get(); System.out.println( "main thread ret = " + ret + " " + Thread.currentThread().getName()); } } |
综上,类图关系如下:
四、CompletableFuture
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public class CompletableFutureDemo { private static ExecutorService threadPool = new ThreadPoolExecutor( 2 , 5 , 1L, TimeUnit.SECONDS, new LinkedBlockingDeque<>( 3 ), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy() ); public static void main(String[] args) { CompletableFuture future1 = CompletableFuture.runAsync(() -> { System.out.println( "执行没有返回值的任务" ); }); CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> { System.out.println( "执行有返回值的任务" ); return "abc" ; }); CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> { System.out.println( "线程池执行有返回值的任务" ); return "123" ; }, threadPool); future1.join(); System.out.println(future2.join()); System.out.println(future3); threadPool.shutdown(); } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异