线程池
来源:互联网 发布:不调用淘宝客api 编辑:程序博客网 时间:2024/06/05 07:54
线程池就是一个可以装线程的一个容器,线程池一般有三种
1固定线程池
ExecutorService threadPool = Executors.newFixedThreadPool(3);//开启线程池,固定的线程池参数3 表示限制放入线程池的线程数
2缓存线程池
Executor threadPool = Executors.newCachedThreadPool();//开启缓存线程池,根据需要,自定添加线程
3单例线程池
Executor threadPool = Executors.newSingleThreadExecutor();//创建单一线程池,线程死掉后,会创建替补,即接班人,保证有一个线程。
线程池的启动方式如下
threadPool.execute(new Runnable() {@Overridepublic void run() { System.out.println(Thread.currentThread().getName()+" is looping of "+j+"for task of"+ task); }});
一般是先往线程池里面添加任务后再执行。
线程池的关闭只有固定线程池才有此方法
threadPool.shutdown();//关闭线程池,只有线程运行完后关闭。threadPool.shutdownNow();//关闭线程池不管没有完成
在此给出一个例子
public class ThreadPoolTest {public static void main(String[] args) {ExecutorService threadPool = Executors.newFixedThreadPool(3);//开启线程池,固定的线程池//Executor threadPool = Executors.newCachedThreadPool();//开启缓存线程池,根据需要,自定添加线程//Executor threadPool = Executors.newSingleThreadExecutor();//创建单一线程池,线程死掉后,会创建替补,即接班人,保证有一个线程。for(int i=1;i<=10;i++){final int task = i;threadPool.execute(new Runnable() {@Overridepublic void run() { for(int j=0;j<10;j++){ try {Thread.sleep(20);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} System.out.println(Thread.currentThread().getName()+" is looping of "+j+"for task of"+ task); }}});}System.out.println("all of 10 ttask have committed");//下面两个方法只在固定线程池中有//threadPool.shutdown();//关闭线程池,只有线程运行完后关闭。//threadPool.shutdownNow();//关闭线程池不管没有完成}}
线程池还有定时器
Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubSystem.out.println("bommbing");}}, 10,2,TimeUnit.SECONDS);//是指十秒炸一次,之后,每隔两秒炸一次
Executors.newScheduledThreadPool(3).schedule(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubSystem.out.println("bommbing");}}, 10,TimeUnit.SECONDS);//每隔十秒炸一次
0 0
- 线程与线程池
- 线程池 线程优先级
- Executor线程,线程池
- 线程、多线程、线程池
- IOS-线程、线程池
- Java线程:线程池
- 线程和线程池
- 线程、多线程、线程池
- 线程、多线程、线程池
- 线程(六)线程池
- ExecutorService(线程池)+线程
- 线程和线程池
- 线程&线程池 简略
- 线程和线程池
- 线程池 线程锁
- 线程、线程池总结
- 线程与线程池
- 线程、锁、线程池
- 三消游戏--冒险王总结
- 使用AIDL双向通信
- 提高 linux 下 firefox 播放 flash 流畅度
- 如何用Spring发送邮件
- Nginx的安装与第三方模块编译
- 线程池
- 第十三章 while and for Loops
- Qcon2015全球软件开发者大会北京站PPT
- Mysql 锁原理很多和Oracle 相似
- iBatis使用SQLServer出现Can't start a cloned connection while in manual transaction mode.错误
- C#中的ComboBox用法
- 多态性
- viewpager详解
- Java 接口