背景:经常创建或销毁,使用量大,并发情况,性能影响大
思路:提前创多个线程,放线程池中,使用直接拿,用完放回池,可避免频繁创建销毁,重复利用,类似交通工具
好处:
减少创建新线程时间
重复利用线程池中线程,不需每次创建
便于线程管理:
核心池大小
最大线程数
线程没有任务时最多保持多长时间后会终止
使用线程池:
jdk5:ExecutorService和Executors
ExecutorService:线程池接口,子类ThreadPoolExecutor
void execute(Runnable command):执行任务,无返回值,一般执行Runnable
<T>Future<T>submit(Callable)task:执行任务,有返回值,一般来执行Callable
void shutDown():关闭线程池
Executors:工具类,线程池工厂类,用于创建并返回不同类型的线程池
package com.wuming.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; //测试线程池 public class TestPool { public static void main(String[] args) { //1.创建服务,创建线程池 //newFixedThreadPool 参数为:线程池大小 ExecutorService service = Executors.newFixedThreadPool(10); //执行 service.execute(new MyThread()); service.execute(new MyThread()); service.execute(new MyThread()); service.execute(new MyThread()); //2.关闭链接 service.shutdown(); } } class MyThread implements Runnable{ /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see Thread#run() */ @Override public void run() { System.out.println(Thread.currentThread().getName()); } }
pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
pool-1-thread-4