自定义一个简易的java线程池

class ThreadPool {
    //任务队列
    private BlockQueue<Runnable> taskQueue;
    
    //线程数量,用来指定线程集合的最大个数
    private int coreSize;

    // 线程集合
    private List<Worker> workers = new Vector<>();

    //线程等待时间
    private long takeTime;

    //线程等待时间单位
    private TimeUnit takeTimeUnit;

    public ThreadPool (int coreSize, int taskQueueCapacity,long takeTime, TimeUnit takeTimeUnit) {
        this.taskQueue = new BlockQueue<>(taskQueueCapacity);
        this.coreSize = coreSize;
        this.takeTime = takeTime;
        this.takeTimeUnit = takeTimeUnit;

    }

    /**
     * 任务执行方法
     * @param task
     */
    public void execute(Runnable task) {
        synchronized (workers) {
            //如果线程集合中的线程数量小于指定线程数量就新建线程,并添加到线程集合中
            //否则就将任务尝试添加到任务队列中去.如果任务队列已经满了,哪个指定处理策略
            if (workers.size() < coreSize) {
                Worker worker = new Worker(task);
                workers.add(worker);
                worker.start();
            } else {
                taskQueue.tryPut(task, (blockQueue, t) -> {
                    task.run();
                });

            }
        }


    }

    class Worker extends Thread {

        Runnable task;

        public Worker(Runnable task) {
            this.task = task;
        }
        @Override
        public void run() {
            //一个任务执行完之后就会尝试从任务队列里去任务
            while (task != null || (task = taskQueue.take(takeTime, takeTimeUnit)) != null) {
                try {
                    //Thread.sleep(1000);
                    task.run();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    task = null;
                }

            }
            synchronized (workers) {
                workers.remove(this);
            }

        }
    }
}



class BlockQueue<T> {

    private Deque<T> queue = new ArrayDeque<T>();

    private ReentrantLock lock = new ReentrantLock();

    //当任务队列已经满了的条件
    private Condition fullWaitSet = lock.newCondition();

    //当任务队列为空的条件
    private Condition emptyWaitSet = lock.newCondition();

    //任务队列的容量
    private int capacity;

    public BlockQueue(int capacity) {
        this.capacity = capacity;
    }

    public T take() {
        lock.lock();
        try {
            while (queue.isEmpty()) {
                try {
                    emptyWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            fullWaitSet.signal();
            return queue.removeFirst();
        } finally {
            lock.unlock();
        }
    }

    public T take(long time, TimeUnit timeUnit) {
        long nanos = timeUnit.toNanos(time);
        lock.lock();
        try {
            while (queue.isEmpty()) {
                try {
                    if (nanos <= 0) {
                        return null;
                    }
                    nanos = emptyWaitSet.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            fullWaitSet.signal();
            return queue.removeFirst();
        } finally {
            lock.unlock();
        }
    }

    public void tryPut(T t, BiConsumer<BlockQueue<T>, T> consumer) {
        lock.lock();
        try {
            if (queue.size() < capacity) {
                queue.addLast(t);
                emptyWaitSet.signal();
            } else {
                consumer.accept(this, t);
            }
        } finally {
            lock.unlock();
        }
    }

    public void put(T t) {
        System.out.println(queue.size());
        lock.lock();
        try {
            while (queue.size() == capacity) {
                try {
                    fullWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            queue.addLast(t);
        } finally {
            lock.unlock();
        }
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个自定义的可缓存线程池Java代码示例: ``` import java.util.concurrent.*; public class CustomThreadPool { private ThreadPoolExecutor executor; public CustomThreadPool() { int corePoolSize = 0; int maximumPoolSize = 10; long keepAliveTime = 60L; TimeUnit unit = TimeUnit.SECONDS; BlockingQueue<Runnable> workQueue = new SynchronousQueue<>(); executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); } public void execute(Runnable task) { executor.execute(task); } public void shutdown() { executor.shutdown(); } } ``` 在这个例子中,我们使用了Java内置的ThreadPoolExecutor类来创建线程池。这个线程池的特点是: - 初始线程数为0,最大线程数为10,空闲线程超过60秒就会被回收 - 使用SynchronousQueue作为任务队列,这个队列没有容量限制,每个插入操作都必须等待一个相应的删除操作,因此任务会立即被提交到线程池中执行 我们还定义了两个方法,execute和shutdown。execute方法接受一个Runnable任务并将其提交给线程池执行,shutdown方法关闭线程池。使用这个线程池的示例代码如下: ``` public static void main(String[] args) { CustomThreadPool threadPool = new CustomThreadPool(); for (int i = 0; i < 20; i++) { final int taskNum = i; threadPool.execute(() -> { System.out.println("Task " + taskNum + " is running."); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Task " + taskNum + " is completed."); }); } threadPool.shutdown(); } ``` 这个示例代码创建了一个CustomThreadPool对象,然后提交了20个任务给线程池执行。每个任务都会打印出自己的编号,然后等待1秒钟,最后打印出自己完成。注意,在最后一行代码中,我们调用了shutdown方法来关闭线程池,确保程序能够正常退出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值