线程池

使用线程池

  • 背景:经常创建和销毁,使用量特别大的资源,比如并发情况下的线程,对性能的影响很大

  • 思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中,可以避免频繁创建销毁,实现重复利用,类似生活中的公共交通工具

  • 好处

  1. 提高了相应速度(减少了创建新线程的时间)

  2. 降低资源消耗(重复利用线程池中线程,不需要每次都创建)

  3. 便于线程管理(.....)

  • corePoolSize:线程池的核心大小

  • maxximumPoolSize:最大线程数

  • keepAliveTime:线程没有任务时保持多长时间后会终止

使用线程池

  • jdk5.0起来提供了线程池相关Apl:ExecutorService和Executors

  • ExecutorService:真正的线程池接口,常见子类ThreadPoolExecutor

  • void execute(Runnable command):执行任务/命令 ,没有返回值,一般用来执行Runnable

  • < T >Future< T >sub(Callable< T >task):执行任务,有返回值,一般又来执行Callable

  • void shutdown():关闭线程池

  • Executors:工具类,线程池的工厂类,用于创建并返回不同类型的线程池子

package BufferedTest;

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

//测试线程池
public class TestPool {
  public static void main(String[] args) {
      //创建线程池
      //newFixedThreadPool参数为池子大小
      ExecutorService executorService = Executors.newFixedThreadPool(10);
      //实现连接
      executorService.execute(new MyTherad6());//对象点execute(new 线程对象)
      executorService.execute(new MyTherad6());
      executorService.execute(new MyTherad6());
      executorService.execute(new MyTherad6());
      //关闭连接
      executorService.shutdown();
  }

}
class MyTherad6 implements Runnable{
  @Override
  public void run() {
      System.out.println(Thread.currentThread().getName());
  }
}
posted @ 2021-09-11 11:38  πππ·  阅读(36)  评论(0)    收藏  举报