多线程-自定义线程池

Take is cheap, Show me the code.

/**
 * 自定义线程池技术案列
 */
public class ThreadPoolDemo {
    public static void main(String[] args) {
        ThreadPool<Job> threadPool = new DefaultThreadPoolDemo<>();
        IntStream.range(0, 10).forEach(item -> threadPool.execute(new Job()));

        System.out.println("Main thread");
        System.out.println("JobSize: " + threadPool.getJobSize());
        threadPool.shutdown();
    }
}

/**
 * 需要做的任务.
 */
class Job implements Runnable {    
	@Override
    public void run() {        
    	try {
            System.out.println(Thread.currentThread().getName() + " start...");
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {           
        	 e.printStackTrace();
        }
        
        System.out.println(Thread.currentThread().getName() + " end...");
    }
}

/**
 * 线程池基础架构.
 *
 * @param 
 */
interface ThreadPool<Job extends Runnable> {
    void execute(Job job);

    void shutdown();

    void addWorkers(int num);

    void removeWorkers(int num);

    int getJobSize();
}

class DefaultThreadPoolDemo<Job extends Runnable> implements ThreadPool<Job> {

    // 线程池的最大线程数
    private static final int MAX_WORKER_NUMBERS = 10;

    // 线程池的默认线程数
    private static final int DEFAULT_WORKER_NUMBERS = 5;

    // 线程池的最小线程数
    private static final int MIN_WORKERS_NUMBERS = 1;

    // 任务队列
    private final LinkedList<Job> jobs = new LinkedList<>();

    // 工作者队列
    private final List<Worker> workers = Collections.synchronizedList(new ArrayList<>());

    // 工作者线程的数量
    private int workNum = DEFAULT_WORKER_NUMBERS;

    // 线程编号生成器
    private AtomicLong threadNum = new AtomicLong();

    public DefaultThreadPoolDemo() {        
    	initialWorkers(DEFAULT_WORKER_NUMBERS);
    }
    
    public void DefaultThreadPoolDemo(int num) {
        workNum = num > MAX_WORKER_NUMBERS ? MAX_WORKER_NUMBERS : num < MIN_WORKERS_NUMBERS ? MIN_WORKERS_NUMBERS : num;
        initialWorkers(workNum);
    }
    
    @Override
    public void execute(Job job) {        
    	if (job != null) {
            // 添加一个工作, 然后通知worker
            synchronized (jobs) {                
            	jobs.addLast(job);
                /**
                 * 不使用notifyAll, 是因为肯定有worker被唤醒.
                 * 而且避免将等待队列中的线程, 全部移动到阻塞队列中.
                 * 而且只是一个任务, 因此, 只需要保证能够唤醒一个worker即可.
                 */
                jobs.notify();
            }        
        }
    }

    @Override
    public void shutdown() {        
    	for (Worker worker : workers) {
            worker.shutdown();
        }    
    }

    @Override
    public void addWorkers(int num) {        
    	synchronized (jobs) {
            // 当前的工作num.
            int currentWorkerNum = num + this.workNum;
            // 限制增加的worker不能超过MAX_WORKER_NUMBERS
            if (currentWorkerNum > MAX_WORKER_NUMBERS) {                
            	num = MAX_WORKER_NUMBERS - this.workNum; // 能够增加的worker数量
            }
            
            initialWorkers(num);
            this.workNum += num;
        }    
   }

    @Override
    public void removeWorkers(int num) {        
    	synchronized (jobs) {
            if (num > this.workNum) {
                throw new IllegalStateException("超过了当前worker数");
            }
            
            int count = 0;
            while (count < num) {                
            	Worker worker = workers.get(count);
                if (workers.remove(worker)) {                    
                	worker.shutdown();
                    count++;
                }            
            }

            this.workNum -= count;
        }    
   }

    @Override
    public int getJobSize() {        
    	return jobs.size();
    }
    
    private void initialWorkers(int workNum) {
        for (int i = 0; i < workNum; i++) {
            Worker worker = new Worker();
            workers.add(worker);

            Thread thread = new Thread(worker, "Thread-pool-worker-" + threadNum);
            threadNum.getAndIncrement();
            thread.start();
        }    
    }

    /**
     * 工作者
     */
    class Worker implements Runnable {
        // 是否工作
        private volatile boolean running = true;

        @Override
        public void run() {            
        	while (running) {
                Job job;
                synchronized (jobs) {                    
                	while (jobs.isEmpty()) { // 任务队列为空, 则等待.
                        try {                            
                        	jobs.wait();
                        } catch (InterruptedException e) {                            
                        	// 若感知到中断操作, 停止线程返回
                            e.printStackTrace();
                            return;
                        }                    
                 }

                    // 任务队列中存在任务, 获取任务给工作者
                    job = jobs.removeFirst();
                }
                if (job != null) {
                    try {
                        job.run();
                    } catch (Exception e) {                        
                    	// 队job执行过程中的异常捕获.
                    }                
                }
            }
        }

        // 设置此worker休息.
        public void shutdown() {            
        	this.running = false;
        }    
    }
}

你可能感兴趣的:(JAVA,java多线程,自定义,线程池,自定义线程池)