欢迎您的访问
专注架构,Java,数据结构算法,Python技术分享

十、网络编程多线程之线程池

引言

线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务。线程池线程都是后台线程。每个线程都使用默认的堆栈大小,以默认的优先级运行,并处于多线程单元中。如果某个线程在托管代码中空闲(如正在等待某个事件),则线程池将插入另一个辅助线程来使所有处理器保持繁忙。如果所有线程池线程都始终保持繁忙,但队列中包含挂起的工作,则线程池将在一段时间后创建另一个辅助线程但线程的数目永远不会超过最大值。超过最大值的线程可以排队,但他们要等到其他线程完成后才启动。

常用的4中线程池

newSingleThreadExecutor()
创建一个单线程池。这个线程池只有一个线程在工作,也就相当于单线程串行执行任务如果唯一的线程因为异常结束,那么会有一个新的线程代替它,此线程池保证所有任务的执行顺序按照任务的提交顺序执行!!!

newFixedThreadPool()
我的理解这是一个有指定的线程数的线程池,有核心的线程,里面有固定的线程数量,响应的速度快。正规的并发线程,多用于服务器。固定的线程数由系统资源设置。

newCachedThreadPool()
只有非核心线程,最大线程数很大(Int.Max(values)),它会为每一个任务添加一个新的线程,这边有一个超时机制,当空闲的线程超过60s内没有用到的话,就会被回收。缺点就是没有考虑到系统的实际内存大小。

newScheduledThreadPool()
返回一个线程池, 它使用给定的线程数来调度任务,必须指定线程数量参数。

newSingleThreadExecutor()

创建一个单线程池。这个线程池只有一个线程在工作,也就相当于单线程串行执行任务如果唯一的线程因为异常结束,那么会有一个新的线程代替它,此线程池保证所有任务的执行顺序按照任务的提交顺序执行!!!
单线程化的线程池:
有且仅有一个工作线程执行任务
所有任务按照指定顺序执行,即遵循队列的入队出队规则

public class TestExecutor {
   public static void main(String[] args) {
       /**
        * 创建线程池
        */
       ExecutorService executorService = Executors.newSingleThreadExecutor();

       //创建一个Runnable
       Runnable runnable = new Runnable() {
           @Override
           public void run() {
               //为了查看同步效果加上一个for循环
               for (int i = 0; i < 2; i++) {
                   System.out.println(Thread.currentThread().getName() + "====" + i);
               }
           }
       };
       //这里执行线程是顺序执行的
       executorService.execute(runnable);
       executorService.execute(runnable);
       executorService.execute(runnable);

       //线程池结束
       executorService.shutdown();
   }
}
执行结果
pool-1-thread-1====0
pool-1-thread-1====1
pool-1-thread-1====0
pool-1-thread-1====1
pool-1-thread-1====0
pool-1-thread-1====1
可以看出来是同步执行的

newFixedThreadPool()

我的理解这是一个有指定的线程数的线程池,有核心的线程,里面有固定的线程数量,响应的速度快。正规的并发线程,多用于服务器。固定的线程数由系统资源设置。
创建固定大小线程池:
1. 可控制线程最大并发数(同时执行的线程数)
2. 超出的线程会在队列中等待


public class TestExecutor {
  public static void main(String[] args) {
      /**
       * 创建一个固定大小线程池,现在创建的是3个线程
       */
      ExecutorService executorService = Executors.newFixedThreadPool(3);

      //这里执行线程是顺序执行的
      executorService.execute(new MyThread());
      executorService.execute(new MyThread());
      executorService.execute(new MyThread());

      //线程池结束
      executorService.shutdown();
  }
}
class MyThread implements Runnable {

  @Override
  public void run() {
          try {
              for (int i = 0; i < 5; i++) {
                  //为了查看同步效果加上一个for循环
                  Thread.sleep(300);
                  System.out.println(Thread.currentThread().getName() + "====" + i);
              }
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
  }
}

执行结果:
pool-1-thread-1====0
pool-1-thread-3====0
pool-1-thread-2====0
pool-1-thread-1====1
pool-1-thread-3====1
pool-1-thread-2====1
pool-1-thread-2====2
pool-1-thread-3====2
pool-1-thread-1====2
pool-1-thread-2====3
pool-1-thread-3====3
pool-1-thread-1====3
pool-1-thread-2====4
pool-1-thread-3====4
pool-1-thread-1====4

从以上可以看出在线程池中有3条线程在并发执行!!!

newCachedThreadPool()

只有非核心线程,最大线程数很大(Int.Max(values)),它会为每一个任务添加一个新的线程,这边有一个超时机制,当空闲的线程超过60s内没有用到的话,就会被回收。缺点就是没有考虑到系统的实际内存大小。
可缓存线程池:
线程数无限制
有空闲线程则复用空闲线程,若无空闲线程则新建线程
在程序减少频繁创建/销毁线程,减少系统开销
只需要将main方法中的newFixedThreadPool方法修改newCachedThreadPool就可以了。


public class TestExecutor {
   public static void main(String[] args) {
       /**
        * 创建一个缓存线程池
        */
       ExecutorService executorService = Executors.newCachedThreadPool();

       //这里执行线程是顺序执行的
       executorService.execute(new MyThread());
       executorService.execute(new MyThread());
       executorService.execute(new MyThread());

       //线程池结束
       executorService.shutdown();
   }
}

执行结果:
pool-1-thread-1====0
pool-1-thread-2====0
pool-1-thread-3====0
pool-1-thread-2====1
pool-1-thread-1====1
pool-1-thread-3====1
pool-1-thread-1====2
pool-1-thread-2====2
pool-1-thread-3====2
pool-1-thread-3====3
pool-1-thread-2====3
pool-1-thread-1====3
pool-1-thread-1====4
pool-1-thread-3====4
pool-1-thread-2====4

newScheduledThreadPool()

返回一个线程池, 它使用给定的线程数(必须指定线程数量)来调度任务。
定长线程池:
支持定时及周期性任务执行。
该方法必须指定线程数量,直接改造main方法即可其它不变


public static void main(String[] args) {
   /**
    * 创建一个缓存线程池,这个是一个设置固定为3个的线程数
    */
   ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);

   //这里预定在指定的时间之后执行任务。此处延时三秒执行
   scheduledExecutorService.schedule(new MyThread(),3000, TimeUnit.MILLISECONDS);
   scheduledExecutorService.schedule(new MyThread(),3000, TimeUnit.MILLISECONDS);
   scheduledExecutorService.schedule(new MyThread(),3000, TimeUnit.MILLISECONDS);
   //线程池结束
   scheduledExecutorService.shutdown();
}

结果:
pool-1-thread-2====0
pool-1-thread-1====0
pool-1-thread-3====0
pool-1-thread-3====1
pool-1-thread-3====2
pool-1-thread-1====1
pool-1-thread-2====1
pool-1-thread-2====2
pool-1-thread-2====3
pool-1-thread-2====4
pool-1-thread-1====2
pool-1-thread-1====3
pool-1-thread-1====4
pool-1-thread-3====3
pool-1-thread-3====4

解释一下上面的代码使用了 ScheduledExecutorService 类的 schedule 方法,这个方法第一个参数为执行的任务,第二个参数是延迟时间,第三个参数为时间的单位,可以使用TimeUnit 的常量指定 延迟时间单位
注意:以上线程池用的较多的是 newSingleThreadExecutornewFixedThreadPool

赞(1) 打赏
版权归原创作者所有,任何形式转载请联系作者;码农code之路 » 十、网络编程多线程之线程池

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏