java语言 百分网手机站

什么是java线程池框架

时间:2020-12-07 15:28:46 java语言 我要投稿

什么是java线程池框架

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

  一、线程池结构图

  二、示例

  定义线程接口

  6public class MyThread extends Thread {@Overridepublicvoid run() {System.out.println(Thread.currentThread().getName() + "正在执行");}}

  1:newSingleThreadExecutor

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

  输入结果:

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

  2:newFixedThreadPool

  13ExecutorService pool = Executors.newFixedThreadPool(3);Thread t1 = new MyThread();Thread t2 = new MyThread();Thread t3 = new MyThread();Thread t4 = new MyThread();Thread t5 = new MyThread();//将线程放入池中进行执行pool.execute(t1);pool.execute(t2);pool.execute(t3);pool.execute(t4);pool.execute(t5);pool.shutdown();

  输入结果:

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

  3 :newCachedThreadPool

  14ExecutorService pool = Executors.newCachedThreadPool();Thread t1 = new MyThread();Thread t2 = new MyThread();Thread t3 = new MyThread();Thread t4 = new MyThread();Thread t5 = new MyThread();//将线程放入池中进行执行pool.execute(t1);pool.execute(t2);pool.execute(t3);pool.execute(t4);pool.execute(t5);//关闭线程池pool.shutdown();

  输入结果:

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

  4 :ScheduledThreadPoolExecutor

  14ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);pool.scheduleAtFixedRate(new Runnable() {//每隔一段时间就触发异常 @Override public void run() { //throw new RuntimeException(); System.out.println("================"); }}, 1000, 2000, TimeUnit.MILLISECONDS);pool.scheduleAtFixedRate(new Runnable() {//每隔一段时间打印系统时间,证明两者是互不影响的 @Override public void run() { System.out.println("+++++++++++++++++"); }}, 1000, 2000, TimeUnit.MILLISECONDS);

  输入结果:

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

  三、线程池核心参数

  corePoolSize : 池中核心的线程数

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

  keepAliveTime : 当线程数大于核

【什么是java线程池框架】相关文章:

1.java线程池框架解析方法

2.什么是java主线程

3.Java 5线程池使用

4.java中通用的线程池实例代码

5.java多线程介绍

6.java多线程教程

7.什么是Java

8.Java 集合框架