多线程_线程池的几种类型

来源:互联网 发布:美墨边境 知乎 编辑:程序博客网 时间:2024/05/15 10:54


1、线程池一个可以装入n个线程的容器,每次池子里面最多能同时运行n个任务(即n个Runnable对象),任务完了,又可以添加新任务,就好像n个线程为m个任务服务

同时能被服务的任务n个.

2、线程池的种类:

  ①固定线程池:

  ②可缓冲线程池

  ③单线程池:

3、定时器线程池定时器类线程池(在普通线程池上面封装而来)


               示例如下

import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * @author Administrator @zsw 2012-7-20 下午02:31:35 */public class ThreadPoolTest {public static void main(String[] args) {//1、固定线程池:池子里面只有固定数量的线程//ExecutorService threadPool=Executors.newFixedThreadPool(3);//2、可缓存的线程池:线程池里面的线程数量根据任务数量动态变化//ExecutorService threadPool=Executors.newCachedThreadPool();/* * 3、单线程池:线程池里面只有一个线程,与单线程的区别是, * 这个池子里面的线程死了会自己找一个替补 */ ExecutorService threadPool=Executors.newSingleThreadExecutor();   for(int i=1;i<=10;i++){final int task=i;threadPool.execute(new Runnable(){@Overridepublic void run() {for(int j=1;j<=10;j++){System.out.println(Thread.currentThread().getName()+" is loop of "+j+ " for task of "+task);/*try {Thread.sleep(20);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}*/}}});}System.out.println("all of 10 tasks have committed!");threadPool.shutdown();//不再添加新任务了,原来的任务干完,就关掉池子//threadPool.shutdownNow();//立刻关闭池子,同时停掉了正在执行的任务}}import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;/** * @author Administrator @zsw 2012-7-20 下午03:34:11 */public class ScheduledThreadPoolTest {public static void main(String[] args) {// 定时器类线程池(在普通线程池上面封装而来)ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(3);// 1:固定时间后执行一次:5秒后执行一次threadPool.schedule(new Runnable() {@Overridepublic void run() {System.out.println("bombing! 一次");}}, 5, TimeUnit.SECONDS);// 2:固定时候后,按照固定频率不停地执行threadPool.scheduleAtFixedRate(new Runnable() {@Overridepublic void run() {System.out.println("bombing!不停");}}, 5, 2, TimeUnit.SECONDS);threadPool.shutdown();}}


原创粉丝点击