在Java中,可以使用ExecutorService
接口和它的實現類(如ThreadPoolExecutor
)來管理線程池。execute()
方法是Runnable
接口的一個方法,用于在線程池中執行一個任務。以下是如何使用線程池管理任務的示例:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
Runnable
接口的類:class MyTask implements Runnable {
@Override
public void run() {
System.out.println("Task is running in thread: " + Thread.currentThread().getName());
try {
TimeUnit.SECONDS.sleep(2); // 模擬任務執行需要一定的時間
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task is completed.");
}
}
Executors
類創建一個線程池:int numberOfThreads = 5; // 線程池中的線程數量
ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
execute()
方法將任務提交給線程池:for (int i = 0; i < 10; i++) {
MyTask task = new MyTask();
executorService.execute(task);
}
executorService.shutdown();
try {
if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException e) {
executorService.shutdownNow();
}
這個示例創建了一個包含5個線程的線程池,并提交了10個任務。線程池會自動管理線程的創建和執行,當所有任務都完成后,線程池會關閉。