自定义线程池
package com.css.xtbgcloudnbgl.test;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class ThreaPoolTest {
public static 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 static class taskWork implements Runnable {
private int id;
public taskWork(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);
}
@Override
public String toString() {
return "taskWork{" +
"id=" + id +
'}';
}
}
public static class MyThreadPool {
private List<Runnable> tasks = Collections.synchronizedList(new LinkedList<>());
List<Runnable> runnables = new LinkedList<>();
private int num;
private int corePoolSize;
private int maxSize;
private int workSize;
public MyThreadPool(int corePoolSize, int maxSize, int workSize) {
this.corePoolSize = corePoolSize;
this.maxSize = maxSize;
this.workSize = workSize;
}
public void submit(Runnable r) {
if (tasks.size() > workSize) {
runnables.add(r);
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 < maxSize) {
new MyWork("非核心线程:"+ num,tasks).start();
num++;
}else if (num > workSize){
tasks.addAll(runnables);
System.out.println("任务:" + r + "放到新的队列里等待。。。");
} else {
System.out.println("任务:" + r + "被缓存了。。。");
}
}
}
public static class myTest{
public static void main(String[] args) {
MyThreadPool myThreadPool = new MyThreadPool(2,4,20);
for (int i = 0; i < 300; i++) {
taskWork taskWork = new taskWork(i);
myThreadPool.submit(taskWork);
}
}
}
}