天天看点

Java 线程的创建方式四--使用线程池

1.线程池的使用背景:

经常创建和销毁线程,及使用量特别大的资源,比如并发情况下的线程,对计算机性能影响特别大,这时就需要一个能存储这些经常使用的线程的东西,线程池因用而生

2.线程池的实现思路:

  • 提前创建好多个线程,放入线程池中,使用时直接获取,使用后放回池中
  • 可以避免频繁创建和销毁线程,实现重复利用(类似生活中的公共交通工具,使用时借用一下,使用后放回规定地方,无需自己创建一个)

3.使用线程池的好处:

  • 提高响应速度(减少了创建新线程的时间)
  • 降低资源消耗(重复利用线程池中的线程)
  • 便于线程管理:
    • corePoolSize: 核心池的大小
    • maximumPoolSize: 最大线程数
    • keepAliveTime: 线程没有任务时最多保持多长时间后会终止

4.线程池相关API

  • JDK5.0起:

ExecutorService 和 Executors

①ExecutorService:

真正的线程池接口

常见子类 ThreadPoolExecutor

  • void execute(Runnable command):

执行任务/命令,无返回值,一般用来执行Runnable

  • <T>Future<T>submit(callable<T>task):

执行任务,有返回值,一般用来执行Callable

  • void shutdown();

关闭连接池

②Executors:

工具类,线程池的工厂类,用来创建并返回不同类型的线程池

  • Executors,newCachedThreadPool();

//创建一个可根据需要创建新线程的线程池

  • Executors,newFixedThreadPool():

//创建一个可重用固定线程数的线程池

  • Executors.newSingleThreadExecutor();

//创建一个只有一个线程的线程池

  • Executors.newScheduledThreadPool():

//创建一个线程池,它可安排在给定延迟后运行命令或定期执行

eg:

package 线程池;

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

class NumberThread implements Runnable{

    @Override
    public void run() {
        for (int i=0;i<=100;i++){
            if (i%2==0){
                System.out.println(i);
            }
        }
    }
}
class NumberThread1 implements Runnable{

    @Override
    public void run() {
        for (int i=0;i<=100;i++){
            if (i%2!=0){
                System.out.println(i);
            }
        }
    }
}

public class Xiancehngchi {

    public static void main(String[] args) {

        //ExecutorService接口实现类的对象
        //1.提供指定线程数量的线程池
        ExecutorService service = Executors.newFixedThreadPool(10);  //设置线程的数量为10
        //2.执行指定的线程的操作,需要提供实现Runnable接口或Collable接口实现类的对象
        service.execute(new NumberThread());  //执行,适合使用于Runnable
        service.execute(new NumberThread1());   //创建第二个线程
        //service.submit(Collable collable);   //提交,适合使用于Collable
        //3.关闭线程池
        service.shutdown();

    }
}