线程池的使用

        工作两年多了,呆过两家公司,但是都没有接触到高并发的内容,所以在此回顾一些线程知识,打好基础,未来遇到的话也可以轻松一些,于是翻出了以前摘抄的代码自己再敲一遍,并且跟深入的理解一下源码:

代码摘抄地址:https://www.cnblogs.com/zhujiabin/p/5404771.html

洗面会对这几种线程策略进行测试验证以及尝试源码分析:

package com.xx.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
Java通过Executors提供四种线程池,分别为:
newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
 *
 */
public class UseThread {
	public static void main(String[] args) {
		/**
		 * (1) newCachedThreadPool
		 * 创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。示例代码如下:
		 * 线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。
		 */
		ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
		for (int i = 0; i < 10; i++) {  
			   final int index = i;  
			   try {  
			    Thread.sleep(index * 1000);  
			   } catch (InterruptedException e) {  
			    e.printStackTrace();  
			   }  
			   cachedThreadPool.execute(new Runnable() {  
			    public void run() {  
			     System.out.println(index);  
			    }  
			   });  
		 } 
		
		/**
		 * (2) newFixedThreadPool
		 * 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。示例代码如下:
			因为线程池大小为3,每个任务输出index后sleep 2秒,所以每两秒打印3个数字。
			定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()
		 * 
		 */
		ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);  
		  for (int i = 0; i < 10; i++) {  
		   final int index = i;  
		   fixedThreadPool.execute(new Runnable() {  
		    public void run() {  
		     try {  
		      System.out.println(index);  
		      Thread.sleep(2000);  
		     } catch (InterruptedException e) {  
		      e.printStackTrace();  
		     }  
		    }  
		   });  
		  }
		  
		  /**
		   * (3)  newScheduledThreadPool
			创建一个定长线程池,支持定时及周期性任务执行。延迟执行示例代码如下:
		   */
		  ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);  
		  scheduledThreadPool.schedule(new Runnable() {  
		   public void run() {  
		    System.out.println("delay 3 seconds");  
		   }  
		  }, 3, TimeUnit.SECONDS);  
		  /**
		   * 表示延迟3秒执行。

			定期执行示例代码如下:表示延迟1秒后每3秒执行一次。
		   */
		  ScheduledExecutorService scheduledThreadPool2 = Executors.newScheduledThreadPool(5);  
		  scheduledThreadPool2.scheduleAtFixedRate(new Runnable() {  
		   public void run() {  
		    System.out.println("delay 1 seconds, and excute every 3 seconds");  
		   }  
		  }, 1, 3, TimeUnit.SECONDS);  
		  /**
		   * (4) newSingleThreadExecutor
			创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。示例代码如下:
		   */
		  ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();  
		  for (int i = 0; i < 10; i++) {  
		   final int index = i;  
		   singleThreadExecutor.execute(new Runnable() {  
		    public void run() {  
		     try {  
		      System.out.println(index);  
		      Thread.sleep(2000);  
		     } catch (InterruptedException e) {  
		      e.printStackTrace();  
		     }  
		    }  
		   });  
		  } 
		  /**
		   * 结果依次输出,相当于顺序执行各个任务。
			你可以使用JDK自带的监控工具来监控我们创建的线程数量,运行一个不终止的线程,创建指定量的线程,来观察:
			工具目录:C:\Program Files\Java\jdk1.6.0_06\bin\jconsole.exe
		   */
		  
	}
}

第一种:newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程:


public class Test {
    public static  void  main(String args[]){
        /**
         * 第一种,带缓存的线程池
         */
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

        for (int i=0;i<10;i++){
            int index=i;
            try {
                Thread.sleep(index*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            cachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
            // 当前排队线程数
            int queueSize = ((ThreadPoolExecutor)cachedThreadPool).getQueue().size();
            // 当前活动线程数
            int activeCount = ((ThreadPoolExecutor)cachedThreadPool).getActiveCount();
            // 执行完成线程数
            long completedTaskCount = ((ThreadPoolExecutor)cachedThreadPool).getCompletedTaskCount();
            // 总线程数(排队线程数 + 活动线程数 +  执行完成线程数)
            long taskCount = ((ThreadPoolExecutor)cachedThreadPool).getTaskCount();
            System.out.println("当前排队线程数"+queueSize);
            System.out.println("当前活动线程数"+activeCount);
            System.out.println("执行完成线程数"+completedTaskCount);
            System.out.println("总线程数(排队线程数 + 活动线程数 +  执行完成线程数)"+taskCount);
              System.out.println(index); } }); } }}

执行结果:

这个例子啥也看不出来

第二个:定长线程池,线程池大小初始化时设定好

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
for (int i = 0; i < 10; i++) {
    final int index = i;
    fixedThreadPool.execute(new Runnable() {
        public void run() {
            try {
                System.out.println(index);
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
}
结果很明显,两个一组同时执行


翻一下源码:

    /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *        pool
     * @param keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.
     * @param unit the time unit for the {@code keepAliveTime} argument
     * @param workQueue the queue to use for holding tasks before they are
     *        executed.  This queue will hold only the {@code Runnable}
     *        tasks submitted by the {@code execute} method.
     * @param threadFactory the factory to use when the executor
     *        creates a new thread
     * @param handler the handler to use when execution is blocked
     *        because the thread bounds and queue capacities are reached
     * @throws IllegalArgumentException if one of the following holds:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException if {@code workQueue}
     *         or {@code threadFactory} or {@code handler} is null
     */
//构造方法,我代码里给的空参数,使用的都是默认值,这里解释一下参数:
 public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.acc = System.getSecurityManager() == null ?
                null :
                AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

    /**
     * Executes the given task sometime in the future.  The task
     * may execute in a new thread or in an existing pooled thread.
     *
     * If the task cannot be submitted for execution, either because this
     * executor has been shutdown or because its capacity has been reached,
     * the task is handled by the current {@code RejectedExecutionHandler}.
     *
     * @param command the task to execute
     * @throws RejectedExecutionException at discretion of
     *         {@code RejectedExecutionHandler}, if the task
     *         cannot be accepted for execution
     * @throws NullPointerException if {@code command} is null
     */
//execute实现类,看看做了啥
 public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        /*
         * Proceed in 3 steps:
         *
         * 1. If fewer than corePoolSize threads are running, try to
         * start a new thread with the given command as its first
         * task.  The call to addWorker atomically checks runState and
         * workerCount, and so prevents false alarms that would add
         * threads when it shouldn't, by returning false.
         *
         * 2. If a task can be successfully queued, then we still need
         * to double-check whether we should have added a thread
         * (because existing ones died since last checking) or that
         * the pool shut down since entry into this method. So we
         * recheck state and if necessary roll back the enqueuing if
         * stopped, or start a new thread if there are none.
         *
         * 3. If we cannot queue task, then we try to add a new
         * thread.  If it fails, we know we are shut down or saturated
         * and so reject the task.
         */
        int c = ctl.get();
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
                reject(command);
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        else if (!addWorker(command, false))
            reject(command);
    }

posted @ 2018-04-09 16:53  黑猫先生  阅读(233)  评论(0编辑  收藏  举报