简单的线程池实现 Java

线程池用有限的线程执行无限的任务。我很好奇,这是如何实现的?在看了一些博文和简单的阅读了一下JDK线程池的源代码后,终于明白,原来就是:首先,创建固定数量的线程,然后,这些线程执行提交的Runnable的run方法。基于这个理解,我实现了一个极简的线程池:

package threadpool;

import java.util.LinkedList;

/**
 * 简单的Java线程池
 * 
 * @author liyuncong
 *
 */
public class SimpleThreadPool {
    private LinkedList<Worker> workers;
    private LinkedList<Runnable> tasks;
    private State state = State.RUNNING;

    public SimpleThreadPool(int threadPoolSize) throws IllegalAccessException {
        if (threadPoolSize < 1) {
            throw new IllegalAccessException("线程池大小至少为1");
        }
        workers = new LinkedList<>();
        tasks = new LinkedList<>();
        for (int i = 0; i < threadPoolSize; i++) {
            Worker worker = new Worker(this);
            worker.start();
            workers.add(worker);
        }
    }

    public synchronized void execut(Runnable task) {
        if (this.state == State.RUNNING) {
            this.tasks.add(task);
            notifyAll();
        }
    }

    public synchronized Runnable getNewTask() {
        while (tasks.isEmpty()) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return tasks.remove();
    }

    public synchronized void shutdown() {
        if (this.state == State.TERMINATION) {
            return;
        }

        this.state = State.TERMINATION;
        for (Worker worker : workers) {
            worker.interrupt();
        }
    }

    private static class Worker extends Thread {
        private SimpleThreadPool simpleThreadPool;

        public Worker(SimpleThreadPool simpleThreadPool) {
            this.simpleThreadPool = simpleThreadPool;
        }

        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                simpleThreadPool.getNewTask().run();
            }
        }

    }

    private static enum State {
        RUNNING, TERMINATION;
    }
}
package threadpool;

public class TestSimpleThreadPool {

    public static void main(String[] args) throws IllegalAccessException {
        final SimpleThreadPool simpleThreadPool = new SimpleThreadPool(3);

        for (int i = 0; i < 10; i++) {
            int j = i;
            Runnable task = new Runnable() {

                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "-task" + j);
                }
            };
            simpleThreadPool.execut(task);
            if (j == 7) {
                simpleThreadPool.shutdown();
            }
        }
    }

}

欢迎大家吐槽我的理解和示例。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值