自定义线程池需要什么
需要哪些类
MyTask
@Data
public class MyTask implements Runnable{
private int id;
MyTask(int id) {
this.id = id;
}
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println("线程" + name + "开始执行任务" + id);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程" + name + "完成任务" + id);
}
}
MyWorker
public class MyWorker extends Thread{
private String name;
private List<Runnable> tasks;
MyWorker(String name, List<Runnable> tasks) {
this.name = name;
this.tasks = tasks;
}
@Override
public void run() {
while (true) {
Runnable task = null;
synchronized (tasks) {
while (tasks.isEmpty()) {
try {
tasks.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
task = tasks.remove(0);
}
System.out.println("线程" + name + "开始执行任务");
task.run();
System.out.println("线程" + name + "完成任务");
}
}
}
自定义线程池
- 提交任务:没有超过最大线程数+ 队列长度,可以继续提交,超过则直接舍弃
- 执行任务:如果小于核心线程数,则使用核心线程,小于最大线程数,使用最大线程,否则进入缓存
public class MyThreadPool {
private List<Runnable> tasks = Collections.synchronizedList(new ArrayList<>());
private int num;
private int maxNum;
private int coreNum;
private int queueSize;
public MyThreadPool(int coreNum, int maxNum, int queueSize) {
this.coreNum = coreNum;
this.maxNum = maxNum;
this.queueSize = queueSize;
}
public void submit(Runnable task) {
if (tasks.size() >= maxNum + queueSize) {
System.out.println("任务已满,任务" + task + "被拒绝");
return;
}
tasks.add(task);
execTask(task);
}
private void execTask(Runnable task) {
if (num < coreNum) {
new MyWorker("核心线程" + num, tasks).start();
num++;
} else if (num < maxNum) {
new MyWorker("非核心线程" + num, tasks).start();
num++;
}else {
System.out.println("任务" + task + "被缓存");
}
}
}