线程池的使用

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPool1 { private static final int NUM_OF_THREADS = 5; private ExecutorService executorService; public ThreadPool1(){ executorService=Executors.newFixedThreadPool(NUM_OF_THREADS); } public ThreadPool1(int thread_num){ executorService=Executors.newFixedThreadPool(thread_num); } public ExecutorService getExecutorService(){ return executorService; } public void shutdown(){ executorService.shutdown(); } public boolean isTerminated(){ return executorService.isTerminated(); } public static void main(String[] args) { ThreadPool1 tp = new ThreadPool1(); // 提交任务到线程池 for (int i = 0; i < 10; i++) { final int taskId = i; tp.getExecutorService().submit(() -> { System.out.println("Executing task " + taskId + " on thread " + Thread.currentThread().getName()); }); } // 关闭线程池 tp.shutdown(); while (!tp.isTerminated()) { // 等待所有任务完成 } System.out.println("All tasks are completed."); } }


方案二
public class ThreadPool2 {
private final ThreadPoolExecutor executor;
public ThreadPool2(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit uint, BlockingDeque<Runnable> workQueue){
executor=new ThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
keepAliveTime,
uint,
workQueue,
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);
}
public void execute(Runnable task){
executor.execute(task);
}
public void shutdown(){
executor.shutdown();
}

public static void main(String[] args) {
ThreadPool2 threadPool2=new ThreadPool2(
5,//核心线程数
10,//最大线程数
60L,//空闲线程等待新任务的最大等待时间 60s
TimeUnit.SECONDS,//
new LinkedBlockingDeque<>(100)//工作队列
);
//提交任务到线程池
for (int i=0;i<20;i++){
final int taskID=i;
threadPool2.execute(() -> {
System.out.println("Task "+ taskID + " is running on thread "+Thread.currentThread().getName());
});
}
//关闭线程池
threadPool2.shutdown();
}
}

  

posted @ 2024-03-26 11:14  dmfsimle  阅读(7)  评论(0)    收藏  举报