线程池原理Java

 1 public class ThreadPool {
 2         int maxCount = 3;
 3         AtomicInteger count =new AtomicInteger(0);// 当前开的线程数  count=0
 4         LinkedList<Runnable> runnables = new LinkedList<Runnable>();
 5 
 6         public void execute(Runnable runnable) {
 7             runnables.add(runnable);
 8             if(count.incrementAndGet()<=3){
 9                 createThread();
10             }
11         }
12         private void createThread() {
13             new Thread() {
14                 @Override
15                 public void run() {
16                     super.run();
17                     while (true) {
18                         // 取出来一个异步任务
19                         if (runnables.size() > 0) {
20                             Runnable remove = runnables.remove(0);
21                             if (remove != null) {
22                                 remove.run();
23                             }
24                         }else{
25                             //  等待状态   wake();
26                         }
27                     }
28                 }
29             }.start();
30         }
31     }

代码简单表示了一下线程池的原理,供初学者参考。

说明如下:

runnables是一个异步任务的队列,

execute方法是执行异步任务的方法,由用户调用,其算法是,将所需要执行的异步任务添加到队列中,等待执行,然后如果需要就创建新的线程;

createThread方法就是线程创建的方法,由execute方法调用,其算法是,直接创建一个新的线程,并且,一旦创建,就不需关闭,无限循环执行异步任务队列总的runnable任务;

原文地址:https://www.cnblogs.com/lude313/p/4793080.html