7.22Java线程池的使用

7.22Java线程池的使用

使用线程池中线程对象的步骤

首先由上篇博客明白:--->JDK1.5之后内置了线程池的方法

步骤:

  • 创建线程池对象

  • 创建Runnable接口子类对象(task)

  • 提交Runnable接口子类对象(take task)

  • 关闭线程池(一般不做)

Java中线程池的一些简述

  • 线程池的顶级接口是java.util.concurrent.Executor,但Executor知识一个执行线程的工具

  • 真正的线程池接口:java.util.concurrent.ExecutorService

  • 线程工厂类:java.util.concurrent.Executors

    • 里面提供了一些静态工厂,生成一些常用的线程池

Executors类中创建线程池的方法:--->该类是生产线程池的工厂类
public static ExecutorService newFixedThreadPool(int nThreads){}
//返回线程池对象。(创建的是有界线程池,池中线程个数可以指定最大数量)

使用线程池对象对象的方法:

public Future<?> submit(Runnable task){}
//获取线程池中的某一个线程对象,并执行
/*
Future接口:记录线程任务执行完毕后产生的结果。线程池创建与使用。
*/

线程池的使用步骤

  1. 使用线程池的工厂类Executor里面提供的方法生产一个指定线程数量的线程池

  2. 创建一个类,实现Runnable接口,重写run方法,设置线程任务

  3. 调用submit方法,传递线程任务,开启线程,执行run方法

  4. 调用shutdown方法销毁线程池--->不建议执行

实现类代码
package PracticeReview.ThreadPool;


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

/**
* 使用JDK 1.5之后提供的Executor类创建线程池
* java.util.concurrent.Executor线程池的工厂类,用于生产线程池
* static ExecutorService newFixedThreadPool(int nThreads)
*     创建一个线程池,该线程池重用固定数量的从共享无界队列中运行的线程。
* 入参:
*     int nThreads:创建线程池中包含的线程数量
* 返回值:
*     返回ExecutorService接口的实现对象,使用ExecutorService接口接收(面向接口编程)
*     --->使用接口去接收对象,不用关注返回的实现类是谁!!!
*     --->该接口必须继承了方法的实现类!!!
* java.util.current.ExecutorService:线程池接口
*     用来从线程池中获取线程,调用start方法,执行线程任务
*         Future<?> submit(Runnable task)--->方法
*         void shutdown()--->关闭、销毁线程池的方法
* @since JDK 1.8
* @date 2021/07/22
* @author Lucifer
*/
public class ThreadPoolDemoNo1 {
   public static Runnable getThreadPool(Runnable runnable){
       //使用线程池的工厂类Executor里面提供的方法生产一个指定线程数量的线程池
       ExecutorService es = Executors.newFixedThreadPool(2); //返回一个线程池的实现类,用接口来接收

       //调用submit方法,获取线程,执行线程任务
       es.submit(runnable);
       es.submit(runnable);
       es.submit(runnable);

       return runnable;
       /*
       线程池会一直开启,使用完线程,会自动把线程归还给线程池,线程可以继续使用
        */
  }

   public static void main(String[] args) {
       System.out.println(getThreadPool(new RunnableImpl())); //pool-1-thread-1This is an answer!
       System.out.println(getThreadPool(new RunnableImpl())); //pool-1-thread-1This is an answer!
       System.out.println(getThreadPool(new RunnableImpl())); //pool-2-thread-2This is an answer!
  }
}
It's a lonely road!!!
原文地址:https://www.cnblogs.com/JunkingBoy/p/15050217.html