您的位置:首页 > 其它

线程池学习笔记 (初识线程池...)

2018-02-23 02:35 183 查看
线程池:
? 为什么使用线程池
1/ 线程缺乏统一管理,占用过多资源,
2/ 缺乏更多的功能 ,如 定时执行 , 定期执行等
--------------------------------------------
使用线程池的优势:
1/重用存在的线程,减少创建,消亡线程的开销
2/有效控制最大并发数 , 提高系统资源使用率
3/ 定时执行,定期执行等
------------------------
线程池位于 java.util.concurrent包中
顶级接口Executor ,真正线程池的接口ExecutorService
java.util.concurrent.Executors类提供了创建线程池的方法
--------------------------------------------------------------
创建线程的方法;
Executors.newCachedThreadPool();//创建一个可以缓存的线程池,有任务时才创建新任务
Executors.newSingleThreadExecutor(); //创建单一线程
Executors.newFixedThreadPool(3); // 创建固定个数线程的线程池
Executors.newScheduledThreadPool(2); // 创建一个固定长度的线程池,而且可以延迟或者定时的方式执行任务*/
-------------------------------------------------------------------------------------------------------------
public class PoolTest {
public static void main(String[] args) {
//创建线程池
ExecutorService executorService = Executors.newCachedThreadPool();
int i= 10;
while (i>0) {
i--;
executorService.execute(new MyRunable(10));
try {
Thread.sleep(100);  //每次执行任务后休眠100毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MyRunable implements Runnable {
int s;
public MyRunable(int s) {
this.s = s;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"========="+s);
}
}
-------------------------------------------------------------------------------------------------------------
结果:
pool-1-thread-1=========10
pool-1-thread-1=========10
pool-1-thread-1=========10
pool-1-thread-1=========10
pool-1-thread-1=========10
pool-1-thread-1=========10
pool-1-thread-1=========10
pool-1-thread-1=========10
pool-1-thread-1=========10
pool-1-thread-1=========10
-------------------------------------------------------------------------------------------------------------
当取消掉休眠后:  可以发现线程池的优势:   可以发现最高的时候有8个线程在执行,其中1,3 线程执行了两次
pool-1-thread-1=========10
pool-1-thread-3=========10

4000
pool-1-thread-4=========10
pool-1-thread-1=========10
pool-1-thread-3=========10
pool-1-thread-5=========10
pool-1-thread-2=========10
pool-1-thread-6=========10
pool-1-thread-7=========10
pool-1-thread-8=========10
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: