当前位置: 移动技术网 > IT编程>开发语言>Java > Java ExecutorService四种线程池使用详解

Java ExecutorService四种线程池使用详解

2019年07月19日  | 移动技术网IT编程  | 我要评论

1.引言

合理利用线程池能够带来三个好处。第一:降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的消耗。第二:提高响应速度。当任务到达时,任务可以不需要的等到线程创建就能立即执行。第三:提高线程的可管理性。线程是稀缺资源,如果无限制的创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,调优和监控。但是要做到合理的利用线程池,必须对其原理了如指掌。

2.线程池使用

executors提供的四种线程 1.newcachedthreadpool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。 2.newfixedthreadpool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。 3.newscheduledthreadpool 创建一个定长线程池,支持定时及周期性任务执行。 4.newsinglethreadexecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(fifo, lifo, 优先级)执行。

1.newcachedthreadpool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。示例如下

executorservice executorservice = executors.newcachedthreadpool();
for(int i=0;i<5;i++){
  final int index = i;
  try {
    thread.sleep(index * 1000);
  } catch (interruptedexception e) {
    e.printstacktrace();
  }
  executorservice.execute(new runnable() {
    @override
    public void run() {
      system.out.println(thread.currentthread().getname() + "," +index);
    }
  });
}
//控制台信息
pool-1-thread-1,0
pool-1-thread-1,1
pool-1-thread-1,2
pool-1-thread-1,3
pool-1-thread-1,4

2.newfixedthreadpool创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。示例如下

executorservice fixedthreadpool = executors.newfixedthreadpool(4);
for(int i=0;i<5;i++) {
  final int index = i;
    fixedthreadpool.execute(new runnable() {
    @override
    public void run() {
      try {
        system.out.println(thread.currentthread().getname() + ", " + index);
        thread.sleep(2000);
      } catch (interruptedexception e) {
        e.printstacktrace();
      }
    }
  });
}
//控制台信息
pool-1-thread-1,0
pool-1-thread-2,1
pool-1-thread-3,2
pool-1-thread-4,3
pool-1-thread-1,4

3.newscheduledthreadpool 创建一个定长线程池,支持周期和定时任务示例如下

scheduledexecutorservice scheduledthreadpool = executors.newscheduledthreadpool(5);
system.out.println("before:" + system.currenttimemillis()/1000);
scheduledthreadpool.schedule(new runnable() {
  @override
  public void run() {
    system.out.println("延迟3秒执行的哦 :" + system.currenttimemillis()/1000);
  }
}, 3, timeunit.seconds);
system.out.println("after :" +system.currenttimemillis()/1000);
//控制台信息
before:1518012703
after :1518012703
延迟3秒执行的哦 :1518012706
system.out.println("before:" + system.currenttimemillis()/1000);
scheduledthreadpool.scheduleatfixedrate(new runnable() {
  @override
  public void run() {
    system.out.println("延迟1秒之后,3秒执行一次:" +system.currenttimemillis()/1000);
  }
}, 1, 3, timeunit.seconds);
system.out.println("after :" +system.currenttimemillis()/1000);

控制台消息
before:1518013024
after :1518013024
延迟1秒之后,3秒执行一次:1518013025
延迟1秒之后,3秒执行一次:1518013028
延迟1秒之后,3秒执行一次:1518013031

4.newsinglethreadexecutor创建一个单线程化的线程池,只会用工作线程来执行任务,保证顺序,示例如下

executorservice singlethreadexecutor = executors.newsinglethreadexecutor();
for (int i=0;i<10;i++) {
  final int index = i;
  singlethreadexecutor.execute(new runnable() {
    @override
    public void run() {
      try {
         system.out.println(thread.currentthread().getname() + "," + index);
        thread.sleep(2000);
      } catch (interruptedexception e) {
        e.printstacktrace();
      }
    }
  });
}

控制台信息
pool-1-thread-1,0
pool-1-thread-1,1
pool-1-thread-1,2
pool-1-thread-1,3
pool-1-thread-1,4

向线程池提交任务 threadpoolexecutor类中execute()和submit()区别 execute()方法实际上是executor中声明的方法,在threadpoolexecutor进行了具体的实现,这个方法是threadpoolexecutor的核心方法,通过这个方法可以向线程池提交一个任务,交由线程池去执行。

submit()方法是在executorservice中声明的方法,在abstractexecutorservice就已经有了具体的实现,在threadpoolexecutor中并没有对其进行重写,这个方法也是用来向线程池提交任务的,但是它和execute()方法不同,它能够返回任务执行的结果,通过源码查看submit()方法的实现,会发现它实际上还是调用的execute()方法,只不过它利用了future来获取任务执行结果。

/**
 * @throws rejectedexecutionexception {@inheritdoc}
 * @throws nullpointerexception    {@inheritdoc}
 */
public future<?> submit(runnable task) {
  if (task == null) throw new nullpointerexception();
  runnablefuture<void> ftask = newtaskfor(task, null);
  execute(ftask);
  return ftask;
}

线程池的关闭 我们可以通过调用线程池的shutdown或shutdownnow方法来关闭线程池,但是它们的实现原理不同,shutdown的原理是只是将线程池的状态设置成shutdown状态,然后中断所有没有正在执行任务的线程。shutdownnow的原理是遍历线程池中的工作线程,然后逐个调用线程的interrupt方法来中断线程,所以无法响应中断的任务可能永远无法终止。shutdownnow会首先将线程池的状态设置成stop,然后尝试停止所有的正在执行或暂停任务的线程,并返回等待执行任务的列表。

只要调用了这两个关闭方法的其中一个,isshutdown方法就会返回true。当所有的任务都已关闭后,才表示线程池关闭成功,这时调用isterminaed方法会返回true。至于我们应该调用哪一种方法来关闭线程池,应该由提交到线程池的任务特性决定,通常调用shutdown来关闭线程池,如果任务不一定要执行完,则可以调用shutdownnow。

3.  线程池的分析

流程分析:线程池的主要工作流程如下图: java线程池主要工作流程

从上图我们可以看出,当提交一个新任务到线程池时,线程池的处理流程如下:

  1. 首先线程池判断基本线程池是否已满?没满,创建一个工作线程来执行任务。满了,则进入下个流程。
  2. 其次线程池判断工作队列是否已满?没满,则将新提交的任务存储在工作队列里。满了,则进入下个流程。
  3. 最后线程池判断整个线程池是否已满?没满,则创建一个新的工作线程来执行任务,满了,则交给饱和策略来处理这个任务。

**源码分析。**上面的流程分析让我们很直观的了解的线程池的工作原理,让我们再通过源代码来看看是如何实现的。线程池执行任务的方法如下:

public void execute(runnable command) {
  if (command == null)
    throw new nullpointerexception();
  int c = ctl.get();
  if (workercountof(c) < corepoolsize) {
    if (addworker(command, true))
      return;
    c = ctl.get();
  }
  if (isrunning(c) && workqueue.offer(command)) {
    int recheck = ctl.get();
    if (! isrunning(recheck) && remove(command))
      reject(command);
    else if (workercountof(recheck) == 0)
      addworker(null, false);
  }
  else if (!addworker(command, false))
    reject(command);
}

工作线程。线程池创建线程时,会将线程封装成工作线程worker,worker在执行完任务后,还会无限循环获取工作队列里的任务来执行。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网