一、编写任务类(MyTask)
public class MyTask implements Runnable {
private int id;
public MyTask(int id) {
this.id = id;
}
@Override
public void run() {
String name = Thread.currentThread().getName();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程:"+name+" 完成了任务:"+id);
}
@Override
public String toString() {
return "MyTask{" +
"id=" + id +
'}';
}
}
二、编写线程类
public class MyWork extends Thread {
private String name;
private List<Runnable> tasks;
public MyWork(String name, List<Runnable> tasks) {
super(name);
this.tasks = tasks;
}
@Override
public void run() {
while (tasks.size() > 0){
Runnable r = tasks.remove(0);
r.run();
}
}
}
三、编写线程池
public class MyThreadPool {
List<Runnable> tasks = Collections.synchronizedList(new LinkedList<>());
private int num;
private int corePoolSize;
private int maxPoolSize;
private int workSize;
public MyThreadPool(int corePoolSize, int maxPoolSize, int workSize) {
this.corePoolSize = corePoolSize;
this.maxPoolSize = maxPoolSize;
this.workSize = workSize;
}
public void submit(Runnable r){
if(tasks.size() >= workSize){
System.out.println("任务:"+r+" 被抛弃了");
}else {
tasks.add(r);
execTask(r);
}
}
private void execTask(Runnable r) {
if(num < corePoolSize){
new MyWork("核心线程:"+num,tasks).start();
num++;
}else if(num < maxPoolSize){
new MyWork("非核心线程"+num,tasks).start();
num++;
}else{
System.out.println("任务:"+r+"被缓存了");
}
}
}
四、测试类
public class MyTest {
public static void main(String[] args) {
MyThreadPool threadPool = new MyThreadPool(2, 4, 20);
for (int i = 0; i < 10; i++) {
MyTask task = new MyTask(i);
threadPool.submit(task);
}
}
}