多线程_线程池的几种类型
来源:互联网 发布:美墨边境 知乎 编辑:程序博客网 时间: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();}}
- 多线程_线程池的几种类型
- NullPointerException 的几种类型
- Doctype的几种类型
- 排序的几种类型
- result_type的几种类型
- Dialog的几种类型
- 几种类型的toast
- DOCTYPE的几种类型
- NAT的几种类型
- Doctype的几种类型
- Toast的几种类型
- 进阶9_多线程3_线程池的基本
- Java线程池的种类
- 09_张孝祥_多线程_java5线程并发库的应用_线程池
- 多线程的使用方式和线程之间同步种类
- 多线程_几种定时器的写法
- 多线程_几种定时器的写法
- 开发MOSS的几种类型
- Ubuntu 12.04 软件管理
- 湖南科技大学OJ Ignatius and the Princess I 加强
- 关于hibernate查询
- 多线程_线程范围内数据共享
- 多线程_普通锁和读写锁
- 多线程_线程池的几种类型
- 我的移植经验之谈,简单的Rom移植教程——附移植JoyOS实例
- rhel/linux下如何找出网卡驱动的内核模块名称
- 什么是Spring
- 多线程的文件上传小示例
- Splash界面的实现
- hibernate constrained属性
- __try,__except,__finally,__leave
- Linux AutoMake