下面是一个使用Java线程池的示例代码:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;public class ThreadPoolExample {public static void main(String[] args) {// 创建一个固定大小的线程池,大小为5ExecutorService executor = Executors.newFixedThreadPool(5);// 创建10个任务并提交给线程池执行for (int i = 0; i < 10; i++) {Runnable worker = new WorkerThread("Task " + i);executor.execute(worker);}// 关闭线程池executor.shutdown();while (!executor.isTerminated()) {}System.out.println("All tasks are completed");}
}class WorkerThread implements Runnable {private String task;public WorkerThread(String task) {this.task = task;}@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + " Start. Task = " + task);processTask();System.out.println(Thread.currentThread().getName() + " End.");}private void processTask() {try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}}
}
这段代码创建了一个固定大小为5的线程池,然后创建了10个任务并提交给线程池执行。每个任务打印一条消息,并休眠2秒钟模拟任务的处理。最后,主线程等待所有任务完成后输出"All tasks are completed"。