网站首页 语言 会计 电脑 医学 资格证 职场 文艺体育 范文
当前位置:书香门第 > 计算机 > java语言

什么是java线程池框架

栏目: java语言 / 发布于: / 人气:1.1W

多线程程序员面试时常常会面对的问题,对多线程概念的掌握和理解水平,也常常被用来衡量一个人的编程实力。不错,普通的.多线程已经不容易了。

什么是java线程池框架

一、线程池结构图

二、示例

定义线程接口

6public class MyThread extends Thread {@Overridepublicvoid run() {tln(entThread()ame() + "正在执行");}}

1:newSingleThreadExecutor

10ExecutorService pool = Executors. newSingleThreadExecutor();Thread t1 = new MyThread();Thread t2 = new MyThread();Thread t3 = new MyThread();//将线程放入池中进行执行ute(t1);ute(t2);ute(t3);//关闭线程池down();

输入结果:

3pool-1-thread-1正在执行pool-1-thread-1正在执行pool-1-thread-1正在执行

2:newFixedThreadPool

13ExecutorService pool = ixedThreadPool(3);Thread t1 = new MyThread();Thread t2 = new MyThread();Thread t3 = new MyThread();Thread t4 = new MyThread();Thread t5 = new MyThread();//将线程放入池中进行执行ute(t1);ute(t2);ute(t3);ute(t4);ute(t5);down();

输入结果:

4pool-1-thread-1正在执行pool-1-thread-2正在执行pool-1-thread-1正在执行pool-1-thread-2正在执行

3 :newCachedThreadPool

14ExecutorService pool = achedThreadPool();Thread t1 = new MyThread();Thread t2 = new MyThread();Thread t3 = new MyThread();Thread t4 = new MyThread();Thread t5 = new MyThread();//将线程放入池中进行执行ute(t1);ute(t2);ute(t3);ute(t4);ute(t5);//关闭线程池down();

输入结果:

5pool-1-thread-2正在执行pool-1-thread-4正在执行pool-1-thread-3正在执行pool-1-thread-1正在执行pool-1-thread-5正在执行

4 :ScheduledThreadPoolExecutor

14ScheduledExecutorService pool = cheduledThreadPool(2);duleAtFixedRate(new Runnable() {//每隔一段时间就触发异常 @Override public void run() { //throw new RuntimeException(); tln("================"); }}, 1000, 2000, ISECONDS);duleAtFixedRate(new Runnable() {//每隔一段时间打印系统时间,证明两者是互不影响的 @Override public void run() { tln("+++++++++++++++++"); }}, 1000, 2000, ISECONDS);

输入结果:

4================+++++++++++++++++++++++++++++++++++++++++++++++++++

三、线程池核心参数

corePoolSize : 池中核心的线程数

maximumPoolSize : 池中允许的最大线程数。

keepAliveTime : 当线程数大于核

Tags:JAVA 线程 框架