完整的Java線程池示例代碼
下面是一個完整的Java線程池示例代碼,包括線程池的創(chuàng)建、提交任務(wù)、獲取任務(wù)執(zhí)行結(jié)果、關(guān)閉線程池等操作:
import java.util.concurrent.*;
public class ThreadPoolExample {
? ? public static void main(String[] args) {
? ? ? ? // 創(chuàng)建線程池
? ? ? ? ExecutorService executor = Executors.newFixedThreadPool(5);
? ? ? ? // 提交任務(wù)
? ? ? ? executor.submit(new Runnable() {
? ? ? ? ? ? public void run() {
? ? ? ? ? ? ? ? System.out.println("Task 1 is running in thread " + Thread.currentThread().getName());
? ? ? ? ? ? }
? ? ? ? });
? ? ? ? Future<Integer> future = executor.submit(new Callable<Integer>() {
? ? ? ? ? ? public Integer call() throws Exception {
? ? ? ? ? ? ? ? System.out.println("Task 2 is running in thread " + Thread.currentThread().getName());
? ? ? ? ? ? ? ? return 1 + 2;
? ? ? ? ? ? }
? ? ? ? });
? ? ? ? // 獲取任務(wù)執(zhí)行結(jié)果
? ? ? ? try {
? ? ? ? ? ? Integer result = future.get();
? ? ? ? ? ? System.out.println("Task 2 result is " + result);
? ? ? ? } catch (InterruptedException | ExecutionException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? ? ? // 關(guān)閉線程池
? ? ? ? executor.shutdown();
? ? }
}
上述代碼創(chuàng)建了一個大小為5的固定線程池,然后向線程池提交了兩個任務(wù),一個是實(shí)現(xiàn)了Runnable接口的匿名類,另一個是實(shí)現(xiàn)了Callable接口的匿名類。接著使用Future接口獲取了Callable任務(wù)的執(zhí)行結(jié)果,并打印輸出結(jié)果。最后關(guān)閉了線程池。
怎么等待線程都執(zhí)行完
可以使用Java中的CountDownLatch類來等待線程都執(zhí)行完畢。
CountDownLatch是一個同步工具類,它可以讓某個線程等待直到倒計時結(jié)束,再開始執(zhí)行。在創(chuàng)建CountDownLatch時,需要傳入一個倒計時的計數(shù)器,調(diào)用CountDownLatch的countDown()方法可以將計數(shù)器減1,調(diào)用await()方法可以讓當(dāng)前線程等待,直到計數(shù)器變?yōu)?才會繼續(xù)執(zhí)行。
以下是一個示例代碼,展示了如何使用CountDownLatch等待多個線程都執(zhí)行完畢:
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class WaitThreadExample {
? ? public static void main(String[] args) {
? ? ? ? int nThreads = 5;
? ? ? ? CountDownLatch latch = new CountDownLatch(nThreads);
? ? ? ? ExecutorService executor = Executors.newFixedThreadPool(nThreads);
? ? ? ? for (int i = 0; i < nThreads; i++) {
? ? ? ? ? ? executor.submit(new Runnable() {
? ? ? ? ? ? ? ? public void run() {
? ? ? ? ? ? ? ? ? ? // 線程執(zhí)行任務(wù)
? ? ? ? ? ? ? ? ? ? System.out.println("Thread " + Thread.currentThread().getName() + " is running");
? ? ? ? ? ? ? ? ? ? // 計數(shù)器減1
? ? ? ? ? ? ? ? ? ? latch.countDown();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? });
? ? ? ? }
? ? ? ? // 等待所有線程執(zhí)行完畢
? ? ? ? try {
? ? ? ? ? ? latch.await();
? ? ? ? } catch (InterruptedException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? ? ? // 關(guān)閉線程池
? ? ? ? executor.shutdown();
? ? ? ? System.out.println("All threads have finished executing");
? ? }
}
上述代碼創(chuàng)建了一個大小為5的固定線程池,并向線程池提交了5個任務(wù)。每個任務(wù)在執(zhí)行完畢后,都會將計數(shù)器減1。最后使用CountDownLatch的await()方法等待計數(shù)器變?yōu)?,即所有任務(wù)都執(zhí)行完畢。當(dāng)計數(shù)器為0時,會輸出"All threads have finished executing"。最后關(guān)閉了線程池。