上文中我们讲了线程池的简单使用,这里我们来讲一下如何简单实现一个自己的线程池
本文实现这个线程池所达到的效果是:用户给出线程数目,程序根据用户给出的数创建固定数目的线程
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() {@Overridepublic void run() {System.out.println("任务" + id);}});}}
}
运行结果