知足常乐|Java线程池原理,这一篇就够了( 二 )

核心代码就从任务队列中不断取出runable对象(即MyTask)并执行 。
excute()只是将任务(MyTask)加入到队列(BlockQueue)中 。
//执行任务 只是把任务加进任务队列 , 什么时候执行由线程管理器决定public void execute(Runnable task){try {taskQueue.put(task);} catch (InterruptedException e) {e.printStackTrace();}}测试代码:
public static void main(String args[]) throws InterruptedException{ThreadPool threadPool = new ThreadPool(5,100);threadPool.execute(new MyTask("testA"));threadPool.execute(new MyTask("testD"));threadPool.execute(new MyTask("testB"));threadPool.execute(new MyTask("testE"));threadPool.execute(new MyTask("testF"));System.out.println(threadPool);Thread.sleep(10000);threadPool.destroy();System.out.println(threadPool);}运行截图:
【知足常乐|Java线程池原理,这一篇就够了】WorkThread num is :5 wait task num is :117 ready exec :com.lxxl.flowlayout.ThreadPool$MyTask@17a4622316 ready exec :com.lxxl.flowlayout.ThreadPool$MyTask@5639218214 ready exec :com.lxxl.flowlayout.ThreadPool$MyTask@de7a04c15 ready exec :com.lxxl.flowlayout.ThreadPool$MyTask@2b036cd118 ready exec :com.lxxl.flowlayout.ThreadPool$MyTask@10469abfready to close pool``````WorkThread num is :5 wait task num is :0引用美团知乎博客的一张图:
知足常乐|Java线程池原理,这一篇就够了