java的自定义线程池
时间: 2023-10-17 15:57:53 浏览: 105
Java的自定义线程池是指在Java中通过编程的方式创建并配置一个符合特定需求的线程池。在Java中,可以使用ThreadPoolExecutor类来创建自定义线程池。通过设置参数,可以指定核心线程数、最大线程数、队列容量等属性,以及自定义拒绝策略。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [java自定义线程池总结](https://blog.csdn.net/qq_21225505/article/details/125092169)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
相关问题
java 自定义线程池
Java中可以使用ThreadPoolExecutor类来创建自定义线程池。使用这个类的构造函数可以指定线程池的核心线程数量、最大线程数量、线程存活时间、时间单位、工作队列、线程工厂等参数。例如:
```
int corePoolSize = 10;
int maximumPoolSize = 100;
long keepAliveTime = 10;
TimeUnit unit = TimeUnit.SECONDS;
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(10);
ThreadFactory threadFactory = Executors.defaultThreadFactory();
ThreadPoolExecutor executor = new ThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
keepAliveTime,
unit,
workQueue,
threadFactory);
```
这里创建了一个核心线程数量为10,最大线程数量为100,线程存活时间为10秒,工作队列为ArrayBlockingQueue的线程池。可以使用该线程池的execute()方法来提交任务。
java自定义线程池
以下是Java自定义线程池的示例代码:
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CustomThreadPool {
public static void main(String[] args) {
// 创建一个固定大小的线程池
ExecutorService executor = Executors.newFixedThreadPool(5);
// 提交任务给线程池执行
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("Task " + (i + 1));
executor.execute(worker);
}
// 关闭线程池
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("所有任务执行完毕");
}
}
class WorkerThread implements Runnable {
private String taskName;
public WorkerThread(String taskName) {
this.taskName = taskName;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " 开始执行任务:" + taskName);
try {
// 模拟任务执行时间
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " 完成任务:" + taskName);
}
}
```
阅读全文