多线程技术主要解决处理器单元内多个线程执行的问题,它能够显著减小处理器单元的闲置时间,增长处理器单元的吞吐能力。 java
线程池主要用来解决线程生命周期开销问题和资源不足问题。经过对多个任务重用线程,线程建立的开销就被分摊到了多个任务上了,并且因为在请求到达时线程已经存在,因此消除了线程建立所带来的延迟。这样,就能够当即为请求服务,使应用程序响应更快。另外,经过适当地调整线程池中的线程数目能够防止出现资源不足的状况。
安全
JDK5中提供的Executors工具类能够经过4个静态方法建立4种线程池,以下所示:多线程
(1)Executors.newCachedThreadPool();ide
public static ExecutorService newCachedThreadPool(){ return new ThreadPoolExecutor(0,Integer.MAX_VALUE,60L,TimeUnit.MILLISECONDS,new SynchronousQueue<Runnable>()); }
public static ExecutorService newFixedThreadPool(int nThreads){ return new ThreadPoolExecutor(nThreads,nThreads,0L,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()); }
它用来处理延时任务或定时任务。工具
它接收SchduledFutureTask类型的任务,有两种提交任务的方式:spa
①scheduledAtFixedRate线程
②scheduledWithFixedDelay3d
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); scheduledThreadPool.schedule(new Runnable() { @Override public void run() { System.out.println("delay 3 seconds"); } }, 3, TimeUnit.SECONDS);
表示延迟3秒执行。 blog
scheduledThreadPool.scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println("delay 1 seconds, and excute every 3 seconds"); } }, 1, 3, TimeUnit.SECONDS);
表示延迟1秒后每3秒执行一次。 生命周期
ScheduledExecutorService比Timer更安全,功能更强大。
(4)Executors.newSingleThreadExecutor();
public static ExecutorService newSingleThreadExecutor(){ return new ThreadPoolExecutor(1,1,0L,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()); }
建立一个单线程化的线程池,它只会用惟一的工做线程来执行任务,保证全部任务按照指定顺序(FIFO, LIFO, 优先级)执行。
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); for (int i = 0; i < 10; i++) { final int index = i; singleThreadExecutor.execute(new Runnable() { @Override public void run() { try { System.out.println(index); Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); }
结果依次输出,至关于顺序执行各个任务。
现行大多数GUI程序都是单线程的。
线程池的做用:
减小了建立和销毁线程的次数,每一个工做线程均可以被重复利用,可执行多个任务。根 据系统的环境状况,能够自动或手动设置线程数量,从而达到运行的最佳效果。