• 线程池


    由各个博客总结归纳而来。

    1.线程池的基本思想:

         线程池的基本思想还是一种对象池的思想,开辟一块内存空间,里面存放了众多(未死亡)的线程,池中线程执行调度由池管理器来处理。当有线程任务时,从池中取一个,执行完成后线程对象归池,这样可以避免反复创建线程对象所带来的性能开销,节省了系统的资源。

    2.线程池的核心代码样式

     1 package BackStage;
     2 
     3 import java.util.concurrent.Executors;
     4 
     5 import java.util.concurrent.ExecutorService;
     6 
     7 public class JavaThreadPool {
     8 
     9     public static void main(String[] args) {
    10 
    11     // 创建一个可重用固定线程数的线程池
    12 
    13     ExecutorService pool = Executors.newFixedThreadPool(2);
    14 
    15     // 创建实现了Runnable接口对象,Thread对象当然也实现了Runnable接口
    16 
    17     Thread t1 = new MyThread();
    18 
    19     Thread t2 = new MyThread();
    20 
    21     Thread t3 = new MyThread();
    22 
    23     Thread t4 = new MyThread();
    24 
    25     Thread t5 = new MyThread();
    26 
    27     // 将线程放入池中进行执行
    28 
    29     pool.execute(t1);
    30 
    31     pool.execute(t2);
    32 
    33     pool.execute(t3);
    34 
    35     pool.execute(t4);
    36 
    37     pool.execute(t5);
    38 
    39     // 关闭线程池
    40 
    41     pool.shutdown();
    42 
    43     }
    44 
    45 }
    46 
    47 class MyThread extends Thread {
    48 
    49     @Override
    50 
    51     public void run() {
    52 
    53     System.out.println(Thread.currentThread().getName() + "正在执行。。。");
    54 
    55     }
    56 
    57 }

    3.线程池的类型:

      1.单任务线程池

          ExecutorService pool = Executors.newSingleThreadExecutor();

      2.固定大小的线程池

          ExecutorService poo延迟连接池 = Executors.newFixedThreadPool(2);

      3.可变尺寸的线程池

         ExecutorService pool = Executors.newCachedThreadPool();

      4.延迟连接池

         ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);

      5.单任务延迟连接池

         ScheduledExecutorService pool = Executors.newSingleThreadScheduledExecutor();

      6.自定义线程池

        ThreadPoolExecutor pool = new ThreadPoolExecutor(2,3,2,TimeUnit.MILLISECONDS,bqueue);

        自定义线程池的详细资料见此链接  http://www.infoq.com/cn/articles/java-threadPool/




        

  • 相关阅读:
    POJ 2891 Strange Way to Express Integers 中国剩余定理 模板 数论
    HDU 6185 Covering 矩阵快速幂 递推
    hdoj2796
    hdoj2795【未完待续】
    hdoj【1006】【未完待续】
    hdoj1007【几何】【未完待续】
    位运算【C++学习(计蒜客)】
    poj1664【DFS】
    退出ACM?
    C4-总结
  • 原文地址:https://www.cnblogs.com/adrianlamo/p/3288116.html
Copyright © 2020-2023  润新知