1 package com.test.ThreadPool; 2 3 import java.util.LinkedList; 4 import java.util.List; 5 import java.util.concurrent.atomic.AtomicInteger; 6 /** 7 * 线程池的实现原理 8 * @author Flynn 9 * 10 */ 11 public class ThreadPool { 12 private static ThreadPool pool = null; 13 14 private final int initNum ; //初始化线程数量 15 private volatile AtomicInteger quenLen = new AtomicInteger(0); //任务队列长度,volatile修饰的原子操作不必加入同步模块 16 private ListtaskQuen = new LinkedList () ; //待处理任务队列,涉及其的操作要做线程安全处理(使用linkedlist是因为任务队列插入删除操作比较频繁) 17 private workThread[] threads; 18 private ThreadPool(int num){ 19 this.initNum = num ; 20 threads = new workThread[initNum] ; 21 for(int i=0;i
1 package com.test.ThreadPool; 2 3 import java.util.concurrent.atomic.AtomicInteger; 4 5 public class TestMain { 6 7 /** 8 * @param args 9 * @throws InterruptedException 10 */11 public static void main(String[] args) throws InterruptedException {12 // TODO Auto-generated method stub13 ThreadPool pool = ThreadPool.getPool(4) ;14 new TestMain.myRun() ;15 pool.execute(new myRun(),new myRun(),new myRun(),new myRun()) ;16 pool.execute(new myRun(),new myRun(),new myRun(),new myRun()) ;17 pool.execute(new myRun(),new myRun(),new myRun(),new myRun()) ;18 pool.execute(new myRun(),new myRun(),new myRun(),new myRun()) ;19 pool.detory() ;20 }21 static class myRun implements Runnable{22 private static volatile AtomicInteger len = new AtomicInteger(0); //任务队列长度,原子操作23 @Override24 public void run() {25 // TODO Auto-generated method stub26 System.err.println("任务--"+len.incrementAndGet()+"--执行了");27 }28 }29 }
实验结果:
1 任务--4--执行了 2 任务--3--执行了 3 任务--1--执行了 4 任务--2--执行了 5 任务--7--执行了 6 任务--6--执行了 7 任务--5--执行了 8 任务--10--执行了 9 任务--9--执行了10 任务--8--执行了11 任务--13--执行了12 任务--12--执行了13 任务--11--执行了14 任务--16--执行了15 任务--15--执行了16 任务--14--执行了
可以看到16个任务全部执行了,没有重复,但是打印的顺序不是递增的,那是因为workThread的run()中任务的执行没有放入同步模块,这也就是只管将任务执行但不控制它具体执行的时间