Java手写实现简单线程池

1.线程池源码解析

2.线程池原理图

在这里插入图片描述

说明:

代码实现的是一个简易的线程池,只实现了核心线程数,没有实现最大线程数,即当线程池内线程数到达了coreSize,新来的任务直接放队列,如果队列慢的话直接就走拒绝策略了,没有设置最大线程数maxSize。

3.BlockingQueue

import java.util.ArrayDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class BlockingQueue<T> {

    private ArrayDeque<T> queue;

    private ReentrantLock lock = new ReentrantLock();

    private Condition empty = lock.newCondition();

    private Condition full = lock.newCondition();

    private int maxSize;

    public BlockingQueue(int maxSize) {
        queue = new ArrayDeque<>();
        this.maxSize = maxSize;
    }

    /**
     * 无限期等待任务入队
     */
    public void put(T t) throws InterruptedException {
        lock.lock();
        try {
            while (queue.size() == maxSize) {
                full.await();
            }
            queue.addLast(t);
            empty.signalAll();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 无限期等待获取任务
     */
    public T get() {
        lock.lock();
        T res = null;
        try {
            while (queue.size() == 0) {
                empty.await();
            }
            res = queue.pollFirst();
            full.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            return res;
        }
    }

    /**
     * 指定超时时间入队
     */
    public boolean put(T t, long waitTime, TimeUnit unit) {
        lock.lock();
        try {
            long time = unit.toNanos(waitTime);
            while (queue.size() == maxSize) {
                if (time <= 0) {
                    System.out.println("任务 " + t + " 已经被丢弃");
                    return false;
                }
                /**
                 * @return 传入的等待时间 - 实际等待的时间
                 * @param 需要等待的时间,即使没有被singnal()唤醒只要到了指定的时间也会被唤醒
                 * */
                try {
                    time = full.awaitNanos(time);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            queue.addLast(t);
            empty.signalAll();
            return true;
        } finally {
            lock.unlock();
        }
    }

    /**
     * 指定超时时间获取数据
     */
    public T get(long waitTime, TimeUnit unit) throws InterruptedException {
        lock.lock();
        try {
            long time = unit.toNanos(waitTime);
            while (queue.size() == 0) {
                if (time <= 0) {
                    return null;
                }
                time = empty.awaitNanos(time);
            }
            T t = queue.pollFirst();
            full.signalAll();
            return t;
        } finally {
            lock.unlock();
        }
    }

    /*
     * 尝试向队列添加元素
     * */
    public void tryPut(ThreadPool.RejectPolicy rejectPolicy, T task) {
        lock.lock();
        try {
            //队列满了,走拒绝策略
            if (queue.size() == maxSize) {
                rejectPolicy.reject(this, task);
                //没满,直接添加
            } else {
                queue.addLast(task);
                full.signal();
            }
        } finally {
            lock.unlock();
        }
    }
}

4.ThreadPool

import java.util.HashSet;
import java.util.Set;

public class ThreadPool {
	
    //Worker集合,就是线程池
    Set<Worker> workers;

    BlockingQueue<Runnable> queue;

    int coreSize;

    /**
     * 拒绝策略接口
     */
    @FunctionalInterface
    interface RejectPolicy<T> {
        void reject(BlockingQueue<T> queue, T task);
    }

    private RejectPolicy rejectPolicy;
	
     /**
     * Worker类,实现Runnable接口,当Worker被创建时,
     * 将这个worker对象扔进内部的Thread里去异步执行任务。
     * */
    public class Worker implements Runnable {
		
        //内部的核心属性,Thread类,当Worker创建
        public Thread thread;

        private Runnable task;


        public Worker(Runnable task) {
            this.task = task;
            //异步执行的任务就是当前Worker。
            thread = new Thread(this);
        }

        @Override
        public void run() {
            /**
             *  线程复用原理: while()循环不断阻塞尝试获取任务
             *  1.先执行自己的task
             *  2.从阻塞队列中尝试获取任务,拿到任务继续执行
             * */
            while (task != null || ((task = queue.get()) != null)) {
                task.run();
                //执行完任务,置为NULL
                task = null;
            }
        }
    }

    public ThreadPool(int coreSize, BlockingQueue<Runnable> queue, RejectPolicy<Runnable> rejectPolicy) {
        workers = new HashSet<>();
        this.coreSize = coreSize;
        this.queue = queue;
        this.rejectPolicy = rejectPolicy;
    }

    public void execute(Runnable task) throws InterruptedException {
        if (task == null) {
            throw new NullPointerException();
        }
        //来任务,判断线程数是否小于核心线程数,小于直接开线程处理
        //源码使用的是 ctl属性,获取ctl的低29位,低29位表示线程池中的线程数
        if (workers.size() < coreSize) {
            Worker worker = new Worker(task);
            //将worker添加到wokers集合中
            workers.add(worker);
            //直接调用内部的start,异步执行worker内部的run()方法
            worker.thread.start();
            //线程数达到核心线程,尝试向队列中添加任务,(队列满了,就走拒绝策略)
        } else {
            queue.tryPut(rejectPolicy, task);
        }
    }
}

5.测试

package com.shstart7.手写线程池;

public class Main {

    public static void main(String[] args) throws InterruptedException {
		
        //阻塞队列大小设置为3
        BlockingQueue<Runnable> queue = new BlockingQueue<>(3);
        System.out.println("主线程号: " + Thread.currentThread().getId());

        /*
        * 核心线程数为2
        * 这里使用 同步运行 的拒绝策略。
        * */
        ThreadPool pool = new ThreadPool(2, queue, (q, task) -> task.run());
        for (int i = 0; i < 10; i++) {
            int j = i;
            pool.execute(() -> {
                System.out.println(j + "  执行此任务的线程号:" + Thread.currentThread().getId());
            });
        }
    }
}

测试,表示任务 5 6 7 8都是走到拒绝策略,主线程直接调用了run()方法同步执行了其他的任务都是由线程池中的两个线程执行的。
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
手写一个简单线程池,你可以按照以下步骤进行: 1. 创建一个任务队列,用于存储待执行的任务。 2. 创建一个固定数量的线程池,用于执行任务。 3. 每当有任务提交到线程池时,将任务添加到任务队列中。 4. 线程池中的每个线程会不断从任务队列中获取任务并执行。 5. 执行完一个任务后,线程继续从任务队列中获取下一个任务,并重复执行,直到任务队列为空。 下面是一个简单Java 代码示例: ```java import java.util.LinkedList; import java.util.Queue; public class ThreadPool { private final int poolSize; private final WorkerThread[] workerThreads; private final Queue<Runnable> taskQueue; public ThreadPool(int poolSize) { this.poolSize = poolSize; this.taskQueue = new LinkedList<>(); this.workerThreads = new WorkerThread[poolSize]; for (int i = 0; i < poolSize; i++) { workerThreads[i] = new WorkerThread(); workerThreads[i].start(); } } public void submit(Runnable task) { synchronized (taskQueue) { taskQueue.add(task); taskQueue.notify(); // 唤醒等待的线程 } } private class WorkerThread extends Thread { @Override public void run() { while (true) { Runnable task; synchronized (taskQueue) { while (taskQueue.isEmpty()) { try { taskQueue.wait(); // 等待新任务的到来 } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } } task = taskQueue.poll(); } try { task.run(); // 执行任务 } catch (RuntimeException e) { // 异常处理 } } } } // 使用示例 public static void main(String[] args) { ThreadPool threadPool = new ThreadPool(5); for (int i = 0; i < 10; i++) { final int index = i; threadPool.submit(() -> { System.out.println("Task " + index + " is running."); try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } System.out.println("Task " + index + " is complete."); }); } } } ``` 上述代码中,首先创建了一个任务队列 `taskQueue`,用于存储待执行的任务。然后创建了固定数量的线程池 `workerThreads`,每个线程会不断从任务队列中获取任务并执行。`ThreadPool` 类提供了 `submit` 方法,用于向线程池提交任务。 在 `main` 方法中,我们创建了一个大小为 5 的线程池,并向线程池提交了 10 个任务,每个任务会打印一段文字,并睡眠一秒钟模拟执行任务的耗时。你可以根据实际需求调整线程池的大小和任务的数量。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shstart7

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值