【Java】实现一个自己的线程池

上文中我们讲了线程池的简单使用,这里我们来讲一下如何简单实现一个自己的线程池

本文实现这个线程池所达到的效果是:用户给出线程数目,程序根据用户给出的数创建固定数目的线程

1、框架

首先写定义一个线程池类

class MyThreadPool{
    
}

public class demo3 {
    public static void main(String[] args) throws InterruptedException {
        
    }
}

然后往MyThreadPool类中填充内容

 2、成员变量

首先定义成员变量

由于线程池中需要一个阻塞队列来存放任务,于是我们便先实现一个LinkedBlockingDeque阻塞队列。成员属性设置为私有

private BlockingDeque<Runnable> queue = new LinkedBlockingDeque<Runnable>();

什么是阻塞队列?

 3、submit()方法

线程池类型中还需要书写一个submit()方法用以添加任务

public void submit(Runnable runnable) throws InterruptedException {
    queue.put(runnable);
}

 4、构造方法

在MyThreadPool构造方法中,我们需要创建用户给定数目的线程,并用这些线程去执行队列中的任务

public MyThreadPool(int n){
        for (int i = 0; i < n; i++) {
            int id = i;
            Thread thread = new Thread(()->{
                Runnable runnable = null;
                try {
                    runnable = queue.take();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                runnable.run();
            });
            thread.start();
        }
}

5、完整代码

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

class MyThreadPool{
    private BlockingDeque<Runnable> queue = new LinkedBlockingDeque<Runnable>();

    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
    }

    public MyThreadPool(int n){
        for (int i = 0; i < n; i++) {
            int id = i;
            Thread thread = new Thread(()->{
                Runnable runnable = null;
                try {
                    runnable = queue.take();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                runnable.run();
            });
            thread.start();
        }
    }
}

public class demo3 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool threadPool = new MyThreadPool(10);
        for (int i = 0; i < 10; i++) {
            int id = i;
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("任务" + id);
                }
            });
        }
    }
}

运行结果

 

  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

沙河板混

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

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

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

打赏作者

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

抵扣说明:

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

余额充值