哈爾濱市建設(shè)網(wǎng)站/寧波網(wǎng)絡(luò)推廣產(chǎn)品服務(wù)
🙈作者簡(jiǎn)介:練習(xí)時(shí)長(zhǎng)兩年半的Java up主
🙉個(gè)人主頁:程序員老茶
🙊 ps:點(diǎn)贊👍是免費(fèi)的,卻可以讓寫博客的作者開興好久好久😎
📚系列專欄:Java全棧,計(jì)算機(jī)系列(火速更新中)
💭 格言:種一棵樹最好的時(shí)間是十年前,其次是現(xiàn)在
🏡動(dòng)動(dòng)小手,點(diǎn)個(gè)關(guān)注不迷路,感謝寶子們一鍵三連
目錄
- 課程名:Java
- 內(nèi)容/作用:知識(shí)點(diǎn)/設(shè)計(jì)/實(shí)驗(yàn)/作業(yè)/練習(xí)
- 學(xué)習(xí):Java 創(chuàng)建線程的所有方法
- Java 創(chuàng)建線程的所有方法
- 1. 繼承Thread類
- 2. 實(shí)現(xiàn)Runnable接口
- 3. 實(shí)現(xiàn)Callable接口和FutureTask類
- 4. 使用Executor框架
- 5. 使用Fork/Join框架
- 6. 通過線程池創(chuàng)建線程
- 總結(jié)
課程名:Java
內(nèi)容/作用:知識(shí)點(diǎn)/設(shè)計(jì)/實(shí)驗(yàn)/作業(yè)/練習(xí)
學(xué)習(xí):Java 創(chuàng)建線程的所有方法
Java 創(chuàng)建線程的所有方法
Java中創(chuàng)建線程的方式有很多,本文將介紹以下幾種方法:
- 繼承Thread類
- 實(shí)現(xiàn)Runnable接口
- 實(shí)現(xiàn)Callable接口和FutureTask類
- 使用Executor框架
- 使用Fork/Join框架
- 通過線程池創(chuàng)建線程
1. 繼承Thread類
通過繼承Thread類并重寫其run()方法來創(chuàng)建線程。
class MyThread extends Thread {@Overridepublic void run() {// 線程執(zhí)行的任務(wù)System.out.println("MyThread is running");}
}public class Main {public static void main(String[] args) {MyThread myThread = new MyThread();myThread.start(); // 啟動(dòng)線程}
}
2. 實(shí)現(xiàn)Runnable接口
通過實(shí)現(xiàn)Runnable接口并重寫其run()方法來創(chuàng)建線程。
class MyRunnable implements Runnable {@Overridepublic void run() {// 線程執(zhí)行的任務(wù)System.out.println("MyRunnable is running");}
}public class Main {public static void main(String[] args) {MyRunnable myRunnable = new MyRunnable();Thread thread = new Thread(myRunnable);thread.start(); // 啟動(dòng)線程}
}
3. 實(shí)現(xiàn)Callable接口和FutureTask類
通過實(shí)現(xiàn)Callable接口并實(shí)現(xiàn)call()方法來創(chuàng)建線程,然后使用FutureTask類來獲取線程執(zhí)行的結(jié)果。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;class MyCallable implements Callable<Integer> {@Overridepublic Integer call() throws Exception {// 線程執(zhí)行的任務(wù)System.out.println("MyCallable is running");return 0;}
}public class Main {public static void main(String[] args) {MyCallable myCallable = new MyCallable();FutureTask<Integer> futureTask = new FutureTask<>(myCallable);Thread thread = new Thread(futureTask);thread.start(); // 啟動(dòng)線程try {Integer result = futureTask.get(); // 獲取線程執(zhí)行的結(jié)果System.out.println("Result: " + result);} catch (InterruptedException | ExecutionException e) {e.printStackTrace();}}
}
4. 使用Executor框架
通過Executor框架來創(chuàng)建線程,可以靈活地控制線程的創(chuàng)建、啟動(dòng)、關(guān)閉等。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;class MyRunnable implements Runnable {@Overridepublic void run() {// 線程執(zhí)行的任務(wù)System.out.println("MyRunnable is running");}
}public class Main {public static void main(String[] args) {ExecutorService executorService = Executors.newFixedThreadPool(5); // 創(chuàng)建一個(gè)固定大小的線程池MyRunnable myRunnable = new MyRunnable();executorService.execute(myRunnable); // 提交任務(wù)到線程池executorService.shutdown(); // 關(guān)閉線程池}
}
5. 使用Fork/Join框架
通過Fork/Join框架來創(chuàng)建線程,可以將一個(gè)大任務(wù)拆分成多個(gè)小任務(wù)并行執(zhí)行。
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.ForkJoinPool;class MyRecursiveTask extends RecursiveTask<Integer> {private int start;private int end;public MyRecursiveTask(int start, int end) {this.start = start;this.end = end;}@Overrideprotected Integer compute() {if (end - start <= 10) {// 如果任務(wù)足夠小,直接計(jì)算結(jié)果int sum = 0;for (int i = start; i < end; i++) {sum += i;}return sum;} else {// 如果任務(wù)較大,拆分成兩個(gè)子任務(wù)并行執(zhí)行int mid = (start + end) / 2;MyRecursiveTask leftTask = new MyRecursiveTask(start, mid);MyRecursiveTask rightTask = new MyRecursiveTask(mid, end);leftTask.fork(); // 異步執(zhí)行左子任務(wù)int rightResult = rightTask.compute(); // 同步計(jì)算右子任務(wù)的結(jié)果int leftResult = leftTask.join(); // 等待左子任務(wù)完成并獲取結(jié)果return leftResult + rightResult; // 合并左右子任務(wù)的結(jié)果}}
}public class Main {public static void main(String[] args) {ForkJoinPool forkJoinPool = new ForkJoinPool(); // 創(chuàng)建一個(gè)Fork/Join線程池MyRecursiveTask myRecursiveTask = new MyRecursiveTask(0, 100);int result = forkJoinPool.invoke(myRecursiveTask); // 提交任務(wù)到線程池并獲取結(jié)果System.out.println("Result: " + result);}
}
6. 通過線程池創(chuàng)建線程
Java提供了Executor框架,可以方便地創(chuàng)建和管理線程池。示例代碼如下:
ExecutorService executor = Executors.newFixedThreadPool(5);for (int i = 0; i < 10; i++) {executor.execute(new Runnable() {public void run() {System.out.println("線程開始執(zhí)行");// 線程要執(zhí)行的任務(wù)System.out.println("線程執(zhí)行結(jié)束");}});
}executor.shutdown(); // 關(guān)閉線程池
這段代碼會(huì)創(chuàng)建一個(gè)固定大小為5的線程池,然后提交10個(gè)任務(wù)給線程池執(zhí)行。當(dāng)所有任務(wù)完成后,需要調(diào)用shutdown()方法關(guān)閉線程池。
總結(jié)
以上介紹了Java中常用的創(chuàng)建線程的方法,包括繼承Thread類、實(shí)現(xiàn)Runnable接口、使用Callable和Future接口、以及通過線程池等方式。在實(shí)際開發(fā)中,應(yīng)根據(jù)具體情況選擇合適的創(chuàng)建線程的方法,并注意線程安全的問題。
往期專欄 |
---|
Java全棧開發(fā) |
數(shù)據(jù)結(jié)構(gòu)與算法 |
計(jì)算機(jī)組成原理 |
操作系統(tǒng) |
數(shù)據(jù)庫系統(tǒng) |
物聯(lián)網(wǎng)控制原理與技術(shù) |