线程池

来源:互联网 发布:mac加速的视频播放器 编辑:程序博客网 时间:2024/06/06 11:38

 引言:为了更好的控制多线程,JDK提供了一套Executors,帮助开发人员有效的进行线程控制

1.关于Executors提供的一些线程池以及如何自定义线程池

package com.wpx.threadpool.demo01;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;/** * *  * Executors创建线程池方法 *  newFixedThreadPool()方法,该方法返回一定数量的线程池,该方法的线程数始终不变 * 当有一个任务提交时 ,若线程池中空闲,则立即执行,若没有,则会被暂缓在一个任务队列中等待空闲的线程执行 *  * newSingleThreadExecutor()方 法,创建一个线程的线程池,若空闲则执行,若没有空闲线程则暂缓在任务队列中 *  * newCacheThreadPool()方法,返回一个可根据实际情况调节线程个数的线程池,不限制最大线程数量 * 若有空闲的线程则执行任务,若无则不创建线程并且空闲线程会60秒后自动回收 *  * newScheeduledThreadPool(),该方法返回一个 SchedeExecutorService对象 * 但该线程可以指定线程的数量 *  * @author wangpx */public class demo01 {public static void main(String[] args) {/** *    public static ExecutorService newFixedThreadPool(int nThreads) {        return new ThreadPoolExecutor(nThreads, nThreads,                                      0L, TimeUnit.MILLISECONDS,                                      new LinkedBlockingQueue<Runnable>());    } */ExecutorService pool1 = Executors.newFixedThreadPool(1);/** *    public static ExecutorService newSingleThreadExecutor() {        return new FinalizableDelegatedExecutorService            (new ThreadPoolExecutor(1, 1,                                    0L, TimeUnit.MILLISECONDS,                                    new LinkedBlockingQueue<Runnable>()));    } */ExecutorService executor = Executors.newSingleThreadExecutor();/** *     public static ExecutorService newCachedThreadPool() {        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,                                      60L, TimeUnit.SECONDS,                                      new SynchronousQueue<Runnable>());    } */ExecutorService pool2 = Executors.newCachedThreadPool();/** *   public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {        return new ScheduledThreadPoolExecutor(corePoolSize);    }           public ScheduledThreadPoolExecutor(int corePoolSize) {        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSE CONDS,  //extends ThreadPoolExecutor              new DelayedWorkQueue());    } */ScheduledExecutorService Pool3 = Executors.newScheduledThreadPool(1);/** * 如果上述线程池不能满足你的要求,  你也可以通过自定义的方式来创建 *  * public ThreadPoolExecutor( int corePoolSize,    //核心线程数 int maximumPoolSize, //最大线程数 long keepAliveTime,  //保持活着的时间 TimeUnit unit,    //时间单位 BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejecedExecutionHandler handler{...} ); *//** * 在使用有界队列时 * 有新任务需要执行 * 如果线程池实际线程数小于corePoolSize,则优先创建线程 * 如果大于corePoolSize,则会将任务加入队列 * 若队列已满,在在总线程不大于maximumPoolSize的前提下创建新的线程 *  若大于maximumPoolSize则采用拒绝策略 *  *   *  * JDK拒绝策略 * AbortPolicy直接抛出异常组织系统正常工作 * callRunPolicy 只要线程池未关闭,该策略直接在调用者线程中,运行当前被丢弃的任务 *  DiscardOidestPolicy:丢弃最古老的一个请求,尝试再次提交当前任务 *  DiscardPolicy:丢弃无法处理的任务不予任何处理 *  如果需要自定义拒绝策略可以实现RejectedExecuionHandler接口 *  *  */}}


2.关于scheduledThreadPool

package com.wpx.threadpool.demo01;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.ScheduledFuture;import java.util.concurrent.TimeUnit;/** * scheduledThreadPool * @author wangpx */public class demo02 {public static void main(String[] args) {Task command=new  Task();ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1);ScheduledFuture<?> scheduleAtFixedRate = scheduledThreadPool.scheduleAtFixedRate(command, 6, 2, TimeUnit.SECONDS);}}class Task extends Thread{public void run() { System.out.println("Task");}}


3.线程池中采用有界队列   关于队列
package com.wpx.threadpool.demo01;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;/** * 在使用有界队列时,若有新的任务需要执行,如果线程池实际线程数小于corePoolSize,则优先创建线程 * 若大于corePoolSize,则会将任务加入队列 * 若队列已满,则在总线程不大于maximumPoolSize的前提下,创建新的线程 * 若线程大于maximumPoolSize,则执行拒绝策略,或其他定义方式 *  *  task 1  and named  wpx is runException in thread "main" java.util.concurrent.RejectedExecutionException: Task MyTask [id=6, name=full] rejected from java.util.concurrent.ThreadPoolExecutor@33909752[Running, pool size = 2, active threads = 2, queued tasks = 3, completed tasks = 0]at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1369)at com.wpx.threadpool.demo01.demo03.main(demo03.java:37)task 5  and named  x is runtask 2  and named  wangpx is runtask 3  and named  w is runtask 4  and named  p is run *  * @author wangpx */public class demo03 {public static void main(String[] args) {ThreadPoolExecutor pool = new  ThreadPoolExecutor(1, 2, 60, TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(3)); MyTask m1=new MyTask(1,"wpx");MyTask m2=new MyTask(2,"wangpx");MyTask m3=new MyTask(3,"w");MyTask m4=new MyTask(4,"p");MyTask m5=new MyTask(5,"x");MyTask m6=new MyTask(6,"full");pool.execute(m1);pool.execute(m2);pool.execute(m3);pool.execute(m4);pool.execute(m5);pool.execute(m6);pool.shutdown();}}class MyTask implements Runnable{private int id;private String name;public MyTask(int id, String name) {super();this.id = id;this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "MyTask [id=" + id + ", name=" + name + "]";}@Overridepublic void run() {try {System.out.println("task "+this.id+"  and named  "+this.name +" is run");Thread.sleep(4000);} catch (InterruptedException e) {e.printStackTrace();}}}


4.无界队列
package com.wpx.threadpool.demo01;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;/** * 在使用无界队列linkedBlockingQueue * 与有界队列相比,除非系统资源耗尽,否则无界的任务队列不存在任务入伍失败的情况 *    当有任务到来 *     当前线程数小于corePoolSize时,,则新建线程执行任务,当达到corePoolSize后就不会继续增加 *     后续仍有新的任务加入而没有空间,无界队列会保持快速增长,直到耗尽系统内存 * @author wangpx */public class demo04 implements Runnable{private static AtomicInteger count= new AtomicInteger(0); @Overridepublic void run() {try {Thread.sleep(2000);int temp=count.incrementAndGet();System.out.println("Task "+temp +" is Running ....");} catch (InterruptedException e) {e.printStackTrace();}}public static void main(String[] args) throws Exception{ LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();//new ArrayBlockingQueue(capacity) ThreadPoolExecutor executor = new  ThreadPoolExecutor(5, 20, 120L, TimeUnit.SECONDS, queue);  for(int i='a';i<'z';i++) { executor.execute(new demo04()); } Thread.sleep(1000); System.out.println("queue size "+queue.size()); Thread.sleep(2000);}}