zoukankan      html  css  js  c++  java
  • 线程池的使用

    1.基本方法

    1.固定大小的线程池

    ExecutorService threadPool = Executors.newFixedThreadPool(int nThreads)

    2.缓存线程池

    ExecutorService threadPool = Executors.newCachedThreadPool()

    根据需要创建一个新的线程池,当之前构造的线程可用时会重用之前的线程

    3.单一线程池

    ExecutorService threadPool = Executors.newSingleThreadExecutor()

    思考:

    如果要实现线程死掉之后重新启动的功能, 使用单一线程池是否可行?

    答: 应该是可行的, 因为线程总是在不断地被创建

    4.线程池的调度(schedule)

    示例代码:

    1         //用线程池启动定时器,10s之后运行Runnable
    2         Executors.newScheduledThreadPool(3).schedule(new Runnable(){
    3                 @Override
    4                 public void run() {
    5                     System.out.println("shen_smile");
    6                 }
    7             }, 10, TimeUnit.SECONDS);

    2.全部测试代码本例中, 所有task完成之后会启动定时器, 过5s后会输出shen_smile

     1 public class Test {
     2     public static void main(String[] args) {
     3         //单一线程池
     4         ExecutorService threadPool = Executors.newSingleThreadExecutor();
     5         for(int i=1;i<6;i++){
     6             final int task = i;
     7             threadPool.execute(new Runnable(){
     8                 @Override
     9                 public void run() {
    10                     for(int j=1;j<10;j++){
    11                         try {
    12                             Thread.sleep(20);
    13                         } catch (InterruptedException e) {
    14                             // TODO Auto-generated catch block
    15                             e.printStackTrace();
    16                         }
    17                         System.out.println(Thread.currentThread().getName() + " is looping of " + j + " for task of " + task);
    18                     }
    19                 }
    20             });
    21         }
    22         System.out.println("all of 10 tasks have committed! ");
    23         threadPool.shutdown();
    24         //用线程池启动定时器,10s之后运行Runnable
    25         Executors.newScheduledThreadPool(3).schedule(new Runnable(){
    26                 @Override
    27                 public void run() {
    28                     System.out.println("shen_smile");
    29                 }
    30             }, 10, TimeUnit.SECONDS);
    31     }
    32 }
  • 相关阅读:
    linux中的等待队列
    MapReduce中的作业调度
    hdfs: 数据流(二)
    hdfs: 一个分布式文件系统(一)
    记住这一天
    Partitioning, Shuffle and sort
    从wordcount 开始 mapreduce (C++hadoop streaming模式)
    iOS9 请求出现App Transport Security has blocked a cleartext HTTP (http://)
    Xcode7 下iphone6、6s进行屏幕适配
    隐藏系统的uitabbar
  • 原文地址:https://www.cnblogs.com/shen-smile/p/5137740.html
Copyright © 2011-2022 走看看