您的位置:首页 > 其它

线程池的理解及使用

2018-03-08 17:01 337 查看
1.初识线程池:根据系统自身的环境情况,有效的限制执行线程的数量,使得运行效果达到最佳。线程主要是通过控制执行的线程的数量,超出数量的线程排队等候,等待有任务执行完毕,再从队列最前面取出任务执行。2.线程池作用:减少创建和销毁线程的次数,每个工作线程可以多次使用可根据系统情况调整执行的线程数量,防止消耗过多内存3.使用ExecutorService:线程池接口ExecutorService pool = Executors.常见线程eg:ExecutorService pool = Executors.newSingleThreadExecutor();
4.常见线程池①newSingleThreadExecutor单个线程的线程池,即线程池中每次只有一个线程工作,单线程串行执行任务②newFixedThreadExecutor(n)固定数量的线程池,没提交一个任务就是一个线程,直到达到线程池的最大数量,然后后面进入等待队列直到前面的任务完成才继续执行③newCacheThreadExecutor(推荐使用)可缓存线程池,当线程池大小超过了处理任务所需的线程,那么就会回收部分空闲(一般是60秒无执行)的线程,当有任务来时,又智能的添加新线程来执行。④newScheduleThreadExecutor大小无限制的线程池,支持定时和周期性的执行线程
5.实例publicclassMyThread extends Thread {    @Override    publicvoid run() {        System.out.println(Thread.currentThread().getName() + "执行中。。。");    }}
①newSingleThreadExecutor
publicclassTestSingleThreadExecutor {    publicstaticvoid main(String[] args) {        //创建一个可重用固定线程数的线程池        ExecutorService pool = Executors. newSingleThreadExecutor();        //创建实现了Runnable接口对象        Thread tt1 = new MyThread();        Thread tt2 = new MyThread();        Thread tt3 = new MyThread();        Thread tt4 = new MyThread();        Thread tt5 = new MyThread();        //将线程放入池中并执行        pool.execute(tt1);        pool.execute(tt2);        pool.execute(tt3);        pool.execute(tt4);        pool.execute(tt5);        //关闭        pool.shutdown();    }}result:pool-1-thread-1执行中。。。pool-1-thread-1执行中。。。pool-1-thread-1执行中。。。pool-1-thread-1执行中。。。pool-1-thread-1执行中。。。
②newFixedThreadExecutor(n)
publicclass TestFixedThreadPool {    publicstaticvoid main(String[] args) {        //创建一个可重用固定线程数的线程池        ExecutorService pool = Executors.newFixedThreadPool(2);        //创建实现了Runnable接口对象        Thread t1 = new MyThread();        Thread t2 = new MyThread();        Thread t3 = new MyThread();        Thread t4 = new MyThread();        Thread t5 = new MyThread();        //将线程放入池中进行执行        pool.execute(t1);        pool.execute(t2);        pool.execute(t3);        pool.execute(t4);        pool.execute(t5);        //关闭线程池        pool.shutdown();    }}result:pool-1-thread-1执行中。。。pool-1-thread-2执行中。。。pool-1-thread-1执行中。。。pool-1-thread-2执行中。。。pool-1-thread-1执行中。。。
③newCacheThreadExecutor
publicclass TestCachedThreadPool {    publicstaticvoid main(String[] args) {        //创建一个可重用固定线程数的线程池        ExecutorService pool = Executors.newCachedThreadPool();        //创建实现了Runnable接口对象        Thread t1 = new MyThread();        Thread t2 = new MyThread();        Thread t3 = new MyThread();        Thread t4 = new MyThread();        Thread t5 = new MyThread();        //将线程放入池中进行执行        pool.execute(t1);        pool.execute(t2);        pool.execute(t3);        pool.execute(t4);        pool.execute(t5);        //关闭线程池        pool.shutdown();    }}result:pool-1-thread-1执行中。。。
pool-1-thread-2执行中。。。pool-1-thread-4执行中。。。pool-1-thread-3执行中。。。pool-1-thread-5执行中。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: