欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java中四种线程池的使用示例详解

程序员文章站 2024-02-22 23:32:16
在什么情况下使用线程池? 1.单个任务处理的时间比较短 2.将需处理的任务的数量大 使用线程池的好处: 1.减少在创建和销毁线程上所花的时间以及系统资源的...

在什么情况下使用线程池?

1.单个任务处理的时间比较短

2.将需处理的任务的数量大

使用线程池的好处:

1.减少在创建和销毁线程上所花的时间以及系统资源的开销

2.如不使用线程池,有可能造成系统创建大量线程而导致消耗完系统内存以及”过度切换”。

本文详细的给大家介绍了关于java中四种线程池的使用,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍:

fixedthreadpool

由executors的newfixedthreadpool方法创建。它是一种线程数量固定的线程池,当线程处于空闲状态时,他们并不会被回收,除非线程池被关闭。当所有的线程都处于活动状态时,新的任务都会处于等待状态,直到有线程空闲出来。fixedthreadpool只有核心线程,且该核心线程都不会被回收,这意味着它可以更快地响应外界的请求。

fixedthreadpool没有额外线程,只存在核心线程,而且核心线程没有超时机制,而且任务队列没有长度的限制。

public class threadpoolexecutortest {
 public static void main(string[] args) {
 executorservice fixedthreadpool =executors. newfixedthreadpool(3);
  for (int i =1; i<=5;i++){
  final int index=i ;
  fixedthreadpool.execute(new runnable(){
   @override
   public void run() {
   try {
   system.out.println("第" +index + "个线程" +thread.currentthread().getname());
   thread.sleep(1000);
   } catch(interruptedexception e ) {
    e .printstacktrace();
   }
  }
 
  });
 }
 }
}

cachedthreadpool

由executors的newcachedthreadpool方法创建,不存在核心线程,只存在数量不定的非核心线程,而且其数量最大值为integer.max_value。当线程池中的线程都处于活动时(全满),线程池会创建新的线程来处理新的任务,否则就会利用新的线程来处理新的任务,线程池中的空闲线程都有超时机制,默认超时时长为60s,超过60s的空闲线程就会被回收。和fixedthreadpool不同的是,cachedthreadpool的任务队列其实相当于一个空的集合,这将导致任何任务都会被执行,因为在这种场景下synchronousqueue是不能插入任务的,synchronousqueue是一个特殊的队列,在很多情况下可以理解为一个无法储存元素的队列。从cachedthreadpool的特性看,这类线程比较适合执行大量耗时较小的任务。当整个线程池都处于闲置状态时,线程池中的线程都会因为超时而被停止回收,几乎是不占任何系统资源。

scheduledthreadpool

通过executors的newscheduledthreadpool方式创建,核心线程数量是固定的,而非核心线程是没有限制的,并且当非核心线程闲置时它会被立即回收,scheduledthreadpool这类线程池主要用于执行定时任务和具有固定时期的重复任务。
延迟:

public class threadpoolexecutortest { 
 public static void main(string[] args) {
 scheduledexecutorservice scheduledthreadpool= executors.newscheduledthreadpool(3); 
 scheduledthreadpool.schedule(newrunnable(){  
  @override
  public void run() {
  system.out.println("延迟三秒");
  }
 }, 3, timeunit.seconds);
 }
}

定时:

public class threadpoolexecutortest { 
 public static void main(string[] args) {
 
 scheduledexecutorservice scheduledthreadpool= executors.newscheduledthreadpool(3); 
 scheduledthreadpool.scheduleatfixedrate(newrunnable(){ 
 @override  
 public void run() {
  system.out.println("延迟1秒后每三秒执行一次");
  }
 },1,3,timeunit.seconds);
 }
 
}

singlethreadexecutor

通过executors的newsinglethreadexecutor方法来创建。这类线程池内部只有一个核心线程,它确保所有的任务都在同一个线程中按顺序执行。singlethreadexecutor的意义在于统一所有外界任务一个线程中,这使得这些任务之间不需要处理线程同步的问题

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。