线程学习--线程池
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程学习--线程池相关的知识,希望对你有一定的参考价值。
一、Executor框架
为了更好的控制多线程,jdk提供了一套线程框架Executor,帮助开发人员有效地进行线程控制。他们都在java.util.concurrent包中,是jdk并发包的核心。其中有一个比较重要的类:Executors,他扮演者线程工厂的角色,我们通过Executors创建特定功能的线程池。
Executors创建线程池方法:
newFixedThreadPool()方法,该方法返回一个固定数量的线程池,该方法的线程数始终不变,当有一个任务提交时,若线程池中空闲,则立即执行,若没有,则会被暂缓在一个任务队列中等待有 空闲的线程去执行
newSingleThreadExecutor()方法,创建一个线程的线程池,若空闲则执行,若没有空闲线程则暂缓在任务队列中。
newCachedThreadPool()方法,返回一个可根据实际情况调整线程个数的线程池,不限制最大线程数量,若用空闲的线程则执行任务,若无任务则不创建线程。并且每一个空闲线程会在60秒后自动回收。
newScheduledThreadPool方法,该方法返回一个SchededExecutorService对象,但该线程池可以指定线程的数量。以下为此用法
package com.bjsxt.height.concurrent017; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; class Temp extends Thread { public void run() { System.out.println("run"); } } public class ScheduledJob { public static void main(String args[]) throws Exception { Temp command = new Temp(); ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); ScheduledFuture<?> scheduleTask = scheduler.scheduleWithFixedDelay(command, 5, 1, TimeUnit.SECONDS); } }
二、自定义线程池
若Executors工厂类无法满足我们的需求,可以自己去创建自定义的线程池,其实Executor工厂类里面的创建线程方法其内部实现均用了ThreadPoolExecutor这个类,这个类可以自定义线程。构造方法如下
pbulic ThreadPoolExecutor (int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler){ }
创建有限队列
package threadpoolexecutor; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class UseThreadPoolExecutor1 { public static void main(String[] args) { /** * 在使用有界队列时,若有新的任务需要执行,如果线程池实际线程数小于corePoolSize,则优先创建线程, * 若大于corePoolSize,则会将任务加入队列, * 若队列已满,则在总线程数不大于maximumPoolSize的前提下,创建新的线程, * 若线程数大于maximumPoolSize,则执行拒绝策略。或其他自定义方式。 * */ ThreadPoolExecutor pool = new ThreadPoolExecutor( 1, //coreSize 2, //MaxSize 60, //60 TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3) //指定一种队列 (有界队列) //new LinkedBlockingQueue<Runnable>() , new MyRejected() //, new DiscardOldestPolicy() ); MyTask mt1 = new MyTask(1, "任务1"); MyTask mt2 = new MyTask(2, "任务2"); MyTask mt3 = new MyTask(3, "任务3"); MyTask mt4 = new MyTask(4, "任务4"); MyTask mt5 = new MyTask(5, "任务5"); MyTask mt6 = new MyTask(6, "任务6"); pool.execute(mt1); pool.execute(mt2); pool.execute(mt3); pool.execute(mt4); pool.execute(mt5); pool.execute(mt6); pool.shutdown(); } }
package threadpoolexecutor; public class MyTask implements Runnable { private int taskId; private String taskName; public MyTask(int taskId, String taskName){ this.taskId = taskId; this.taskName = taskName; } public int getTaskId() { return taskId; } public void setTaskId(int taskId) { this.taskId = taskId; } public String getTaskName() { return taskName; } public void setTaskName(String taskName) { this.taskName = taskName; } @Override public void run() { try { System.out.println("run taskId =" + this.taskId); Thread.sleep(5*1000); //System.out.println("end taskId =" + this.taskId); } catch (InterruptedException e) { e.printStackTrace(); } } public String toString(){ return Integer.toString(this.taskId); } }
package threadpoolexecutor; import java.net.HttpURLConnection; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; public class MyRejected implements RejectedExecutionHandler{ public MyRejected(){ } @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { System.out.println("自定义处理.."); System.out.println("当前被拒绝任务为:" + r.toString()); } }
创建无线队列
package com.bjsxt.height.concurrent018; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class UseThreadPoolExecutor2 implements Runnable{ private static AtomicInteger count = new AtomicInteger(0); @Override public void run() { try { int temp = count.incrementAndGet(); System.out.println("任务" + temp); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception{ //System.out.println(Runtime.getRuntime().availableProcessors()); BlockingQueue<Runnable> queue = //new LinkedBlockingQueue<Runnable>(); new ArrayBlockingQueue<Runnable>(10); ExecutorService executor = new ThreadPoolExecutor( 5, //core 10, //max 120L, //2fenzhong TimeUnit.SECONDS, queue); for(int i = 0 ; i < 20; i++){ executor.execute(new UseThreadPoolExecutor2()); } Thread.sleep(1000); System.out.println("queue size:" + queue.size()); //10 Thread.sleep(2000); } }
以上是关于线程学习--线程池的主要内容,如果未能解决你的问题,请参考以下文章