一、简单线程池实现
- 执行器,
- 作用:执行线程,内部存在包含真正执行任务的线程threads
- 其中容器出错的点,是初始化线程之后,需要让线程处于死循环中,这样才可以不断的接受来自队列中的任务,进行执行。
public class MyExecutor {
private final int poolSize;
private final RunnableTaskQueue runnableTaskQueue;
private final List<Thread> threads = new ArrayList<>();
public MyExecutor(int poolSize){
this.poolSize = poolSize;
runnableTaskQueue = new RunnableTaskQueue();
Stream.iterate(1,item->item+1).limit(poolSize).forEach(item->{
initThread();
});
}
private void initThread() {
if(threads.size()<=poolSize){
Thread thread = new Thread(()->{
while (true) {
Runnable task = runnableTaskQueue.getTask();
task.run();
}
});
threads.add(thread);
thread.start();
}
}
public void execute(Runnable runnable){
runnableTaskQueue.addTask(runnable);
}
}
- 任务队列
public class RunnableTaskQueue {
private final LinkedList<Runnable> tasks = new LinkedList<>();
public void addTask(Runnable task){
synchronized (this.tasks){
tasks.add(task);
tasks.notifyAll();
}
}
public Runnable getTask() {
synchronized (this.tasks){
while (tasks.isEmpty()){
System.out.println("线程【"+Thread.currentThread().getName()+"】进入等待状态");
try {
tasks.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return tasks.removeFirst();
}
}
}
- 测试类
public class Test {
public static void main(String[] args) throws IOException {
MyExecutor executor = new MyExecutor(5);
for (int i= 0 ;i<10;i++){
executor.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " execute this task");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
try {
Thread.currentThread().sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.in.read());
}
}