赞
踩
经常的创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。提前创建好多个线程,放入到线程池中,使用时直接获取,使用完放回到线程池中,这样就可以避免频繁创建销毁、实现重复利用。
线程池的好处:
corePoolSize
核心池的大小、maximumPoolSize
最大线程数、keepAliveTime
线程没有任务时最多保持多长时间后会终止JDK5.0起提供了线程池相关API:ExecutorService
和Executors
ExecutorService
ThreadPoolExecutor
。void execute(Runnable command)
:执行任务/命令,没有返回值,一般用来执行Runnable
。< T >Future< T >submit(Callable< T >task)
:执行任务,有返回值,一般用来执行Callable
。void shutdown()
:关闭线程池。Executors
Executors.newCachedThreadPool()
:创建一个可根据需要创建新线程的线程池。import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPool { public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(10); ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor)executorService; threadPoolExecutor.setCorePoolSize(15); //executorService.submit() //适合Callable executorService.execute(new NumberThread()); //适合Runnable executorService.execute(new NumberThread1()); //适合Runnable executorService.shutdown(); } } class NumberThread implements Runnable{ @Override public void run() { for (int i = 0; i <= 100 ; i++) { if(i % 2 == 0){ System.out.println(Thread.currentThread().getName() + ":" + i); } } } } class NumberThread1 implements Runnable{ @Override public void run() { for (int i = 0; i <= 100 ; i++) { if(i % 2 != 0){ System.out.println(Thread.currentThread().getName() + ":" + i); } } } }
Runnable
接口或者Callable
接口实现类的对象。输出结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。