【线程池】

程序启动一个新线程成本是比较高的,因为它涉及到要与操作系统进行交互。而使用线 程池可以很好的提高性能,尤其是当程序中要创建大量生存期很短的线程时,更应该考虑使 用线程池。

线程池里的每一个线程代码结束后,并不会死亡,而是再次回到线程池中成为空闲状态, 等待下一个对象来使用。

在JDK5 之前,我们必须手动实现自己的线程池,从JDK5 开始,Java 内置支持线程池 JDK5 新增了一个Executors 工厂类来产生线程池,有如下几个方法

  public static ExecutorService newCachedThreadPool()

  public static ExecutorService newFixedThreadPool(int nThreads)

  public static ExecutorService newSingleThreadExecutor()

这些方法的返回值是ExecutorService 对象,该对象表示一个线程池,可以执行Runnable 对象或者Callable 对象代表的线程。它提供了如下方法

  Future<?> submit(Runnable task)
  <T> Future<T> submit(Callable<T> task)

案例演示
  创建线程池对象
  创建Runnable 实例
  提交Runnable 实例线程池的好处:线程池里的每一个线程代码结束后,并不会死亡,而是再次回到线程池中成为空闲状态,等待下一个对象来使用。

如何实现线程的代码呢?
A:创建一个线程池对象,控制要创建几个线程对象。
  public static ExecutorService newFixedThreadPool(int nThreads)

B:这种线程池的线程可以执行:
  可以执行Runnable 对象或者Callable 对象代表的线程
  做一个类实现Runnable 接口。
C:调用如下方法即可
  Future<?> submit(Runnable task)
  <T> Future<T> submit(Callable<T> task)
D:我就要结束线程池,可以吗?
  可以。shutdown()

package com.test;

public class MyRunnable implements Runnable {

    @Override
    public void run() {
        for(int x=0;x<10;x++){
            System.out.println(Thread.currentThread().getName()+":"+x);
        }
    }

}
package com.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorsTest {

    public static void main(String[] args) {
        // 创建一个线程池对象,控制要创建几个线程对象。
        ExecutorService pool = Executors.newFixedThreadPool(2);
        // 可以执行Runnable 对象或者Callable 对象代表的线程
        pool.submit(new MyRunnable());
        pool.submit(new MyRunnable());
        //结束线程池
        pool.shutdown();
    }

}

 运行结果:

pool-1-thread-2:0
pool-1-thread-2:1
pool-1-thread-2:2
pool-1-thread-2:3
pool-1-thread-2:4
pool-1-thread-2:5
pool-1-thread-2:6
pool-1-thread-2:7
pool-1-thread-2:8
pool-1-thread-2:9
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
pool-1-thread-1:5
pool-1-thread-1:6
pool-1-thread-1:7
pool-1-thread-1:8
pool-1-thread-1:9
终身学习者
原文地址:https://www.cnblogs.com/zuixinxian/p/9575804.html