服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - JAVA线程池原理实例详解

JAVA线程池原理实例详解

2021-07-27 11:31冬瓜蔡 Java教程

这篇文章主要介绍了JAVA线程池原理,结合实例形式详细分析了java线程池概念、原理、创建、使用方法及相关注意事项,需要的朋友可以参考下

本文实例讲述了java线程池原理。分享给大家供大家参考,具体如下:

线程池的优点

1、线程是稀缺资源,使用线程池可以减少创建和销毁线程的次数,每个工作线程都可以重复使用。

2、可以根据系统的承受能力,调整线程池中工作线程的数量,防止因为消耗过多内存导致服务器崩溃。

线程池的创建

?
1
2
3
4
5
6
public threadpoolexecutor(int corepoolsize,
               int maximumpoolsize,
               long keepalivetime,
               timeunit unit,
               blockingqueue<runnable> workqueue,
               rejectedexecutionhandler handler)
  • corepoolsize:线程池核心线程数量
  • maximumpoolsize:线程池最大线程数量
  • keepalivertime:当活跃线程数大于核心线程数时,空闲的多余线程最大存活时间
  • unit:存活时间的单位
  • workqueue:存放任务的队列
  • handler:超出线程范围和队列容量的任务的处理程序

线程池的实现原理

提交一个任务到线程池中,线程池的处理流程如下:

1、判断线程池里的核心线程是否都在执行任务,如果不是(核心线程空闲或者还有核心线程没有被创建)则创建一个新的工作线程来执行任务。如果核心线程都在执行任务,则进入下个流程。

2、线程池判断工作队列是否已满,如果工作队列没有满,则将新提交的任务存储在这个工作队列里。如果工作队列满了,则进入下个流程。

3、判断线程池里的线程是否都处于工作状态,如果没有,则创建一个新的工作线程来执行任务。如果已经满了,则交给饱和策略来处理这个任务。

JAVA线程池原理实例详解

线程池的源码解读

1、threadpoolexecutor的execute()方法

?
1
2
3
4
5
6
7
8
9
10
11
12
public void execute(runnable command) {
    if (command == null)
      throw new nullpointerexception(); //如果线程数大于等于基本线程数或者线程创建失败,将任务加入队列
    if (poolsize >= corepoolsize || !addifundercorepoolsize(command)) {//线程池处于运行状态并且加入队列成功
      if (runstate == running && workqueue.offer(command)) {
        if (runstate != running || poolsize == 0)
          ensurequeuedtaskhandled(command);
      }//线程池不处于运行状态或者加入队列失败,则创建线程(创建的是非核心线程)
      else if (!addifundermaximumpoolsize(command))//创建线程失败,则采取阻塞处理的方式
        reject(command); // is shutdown or saturated
    }
}

2、创建线程的方法:addifundercorepoolsize(command)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private boolean addifundercorepoolsize(runnable firsttask) {
    thread t = null;
    final reentrantlock mainlock = this.mainlock;
    mainlock.lock();
    try {
      if (poolsize < corepoolsize && runstate == running)
        t = addthread(firsttask);
    } finally {
      mainlock.unlock();
    }
    if (t == null)
      return false;
    t.start();
    return true;
}

我们重点来看第7行:

?
1
2
3
4
5
6
7
8
9
10
11
12
private thread addthread(runnable firsttask) {
    worker w = new worker(firsttask);
    thread t = threadfactory.newthread(w);
    if (t != null) {
      w.thread = t;
      workers.add(w);
      int nt = ++poolsize;
      if (nt > largestpoolsize)
        largestpoolsize = nt;
    }
    return t;
}

这里将线程封装成工作线程worker,并放入工作线程组里,worker类的方法run方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
public void run() {
  try {
    runnable task = firsttask;
    firsttask = null;
    while (task != null || (task = gettask()) != null) {
      runtask(task);
      task = null;
    }
  } finally {
    workerdone(this);
  }
}

worker在执行完任务后,还会通过gettask方法循环获取工作队里里的任务来执行。

我们通过一个程序来观察线程池的工作原理:

1、创建一个线程

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class threadpooltest implements runnable
{
  @override
  public void run()
  {
    try
    {
      thread.sleep(300);
    }
    catch (interruptedexception e)
    {
      e.printstacktrace();
    }
  }
}

2、线程池循环运行16个线程:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static void main(string[] args)
{
    linkedblockingqueue<runnable> queue =
      new linkedblockingqueue<runnable>(5);
    threadpoolexecutor threadpool = new threadpoolexecutor(5, 10, 60, timeunit.seconds, queue);
    for (int i = 0; i < 16 ; i++)
    {
      threadpool.execute(
        new thread(new threadpooltest(), "thread".concat(i + "")));
      system.out.println("线程池中活跃的线程数: " + threadpool.getpoolsize());
      if (queue.size() > 0)
      {
        system.out.println("----------------队列中阻塞的线程数" + queue.size());
      }
    }
    threadpool.shutdown();
}

执行结果:

线程池中活跃的线程数: 1
线程池中活跃的线程数: 2
线程池中活跃的线程数: 3
线程池中活跃的线程数: 4
线程池中活跃的线程数: 5
线程池中活跃的线程数: 5
----------------队列中阻塞的线程数1
线程池中活跃的线程数: 5
----------------队列中阻塞的线程数2
线程池中活跃的线程数: 5
----------------队列中阻塞的线程数3
线程池中活跃的线程数: 5
----------------队列中阻塞的线程数4
线程池中活跃的线程数: 5
----------------队列中阻塞的线程数5
线程池中活跃的线程数: 6
----------------队列中阻塞的线程数5
线程池中活跃的线程数: 7
----------------队列中阻塞的线程数5
线程池中活跃的线程数: 8
----------------队列中阻塞的线程数5
线程池中活跃的线程数: 9
----------------队列中阻塞的线程数5
线程池中活跃的线程数: 10
----------------队列中阻塞的线程数5
exception in thread "main" java.util.concurrent.rejectedexecutionexception: task thread[thread15,5,main] rejected from java.util.concurrent.threadpoolexecutor@232204a1[running, pool size = 10, active threads = 10, queued tasks = 5, completed tasks = 0]
    at java.util.concurrent.threadpoolexecutor$abortpolicy.rejectedexecution(threadpoolexecutor.java:2047)
    at java.util.concurrent.threadpoolexecutor.reject(threadpoolexecutor.java:823)
    at java.util.concurrent.threadpoolexecutor.execute(threadpoolexecutor.java:1369)
    at test.threadtest.main(threadtest.java:17)

从结果可以观察出:

1、创建的线程池具体配置为:核心线程数量为5个;全部线程数量为10个;工作队列的长度为5。
2、我们通过queue.size()的方法来获取工作队列中的任务数。
3、运行原理:

刚开始都是在创建新的线程,达到核心线程数量5个后,新的任务进来后不再创建新的线程,而是将任务加入工作队列,任务队列到达上线5个后,新的任务又会创建新的普通线程,直到达到线程池最大的线程数量10个,后面的任务则根据配置的饱和策略来处理。我们这里没有具体配置,使用的是默认的配置abortpolicy:直接抛出异常。
当然,为了达到我需要的效果,上述线程处理的任务都是利用休眠导致线程没有释放!!!

rejectedexecutionhandler:饱和策略

当队列和线程池都满了,说明线程池处于饱和状态,那么必须对新提交的任务采用一种特殊的策略来进行处理。这个策略默认配置是abortpolicy,表示无法处理新的任务而抛出异常。java提供了4中策略:

1、abortpolicy:直接抛出异常
2、callerrunspolicy:只用调用所在的线程运行任务
3、discardoldestpolicy:丢弃队列里最近的一个任务,并执行当前任务。
4、discardpolicy:不处理,丢弃掉。

我们现在用第四种策略来处理上面的程序:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static void main(string[] args)
{
    linkedblockingqueue<runnable> queue =
      new linkedblockingqueue<runnable>(3);
    rejectedexecutionhandler handler = new threadpoolexecutor.discardpolicy();
    threadpoolexecutor threadpool = new threadpoolexecutor(2, 5, 60, timeunit.seconds, queue,handler);
    for (int i = 0; i < 9 ; i++)
    {
      threadpool.execute(
        new thread(new threadpooltest(), "thread".concat(i + "")));
      system.out.println("线程池中活跃的线程数: " + threadpool.getpoolsize());
      if (queue.size() > 0)
      {
        system.out.println("----------------队列中阻塞的线程数" + queue.size());
      }
    }
    threadpool.shutdown();
}

执行结果:

线程池中活跃的线程数: 1
线程池中活跃的线程数: 2
线程池中活跃的线程数: 2
----------------队列中阻塞的线程数1
线程池中活跃的线程数: 2
----------------队列中阻塞的线程数2
线程池中活跃的线程数: 2
----------------队列中阻塞的线程数3
线程池中活跃的线程数: 3
----------------队列中阻塞的线程数3
线程池中活跃的线程数: 4
----------------队列中阻塞的线程数3
线程池中活跃的线程数: 5
----------------队列中阻塞的线程数3
线程池中活跃的线程数: 5
----------------队列中阻塞的线程数3

这里采用了丢弃策略后,就没有再抛出异常,而是直接丢弃。在某些重要的场景下,可以采用记录日志或者存储到数据库中,而不应该直接丢弃。

设置策略有两种方式:

1、

?
1
2
rejectedexecutionhandler handler = new threadpoolexecutor.discardpolicy();
threadpoolexecutor threadpool = new threadpoolexecutor(2, 5, 60, timeunit.seconds, queue,handler);

2、

?
1
2
threadpoolexecutor threadpool = new threadpoolexecutor(2, 5, 60, timeunit.seconds, queue);
threadpool.setrejectedexecutionhandler(new threadpoolexecutor.abortpolicy());

希望本文所述对大家java程序设计有所帮助。

延伸 · 阅读

精彩推荐