java ThreadPool 线程池

线程池的参数corePoolSize 为核心线程;maximunPoolSize为最大线程;

keepAliveTime为最长生命时间;unit是其时间单位;workQueue任务队列;

handler是过多线程之后的策略

 

对于线程池的处理线程机制,网上有一堆,但是机制核心是优先处理核心线程,优先堆满线程池,初学者建议不用轻易使用拒绝策略,除非是可容忍的线程

 

 

 

package com.test.second;

import java.util.concurrent.ArrayBlockingQueue;  
import java.util.concurrent.BlockingQueue;  
import java.util.concurrent.RejectedExecutionHandler;  
import java.util.concurrent.ThreadPoolExecutor;  
import java.util.concurrent.TimeUnit;  
import java.util.concurrent.atomic.AtomicLong;  
  
public class TimingThreadPool extends ThreadPoolExecutor {  
  
    public TimingThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,  
            BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {  
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);  
    }  
  
    private final ThreadLocal<Long> startTime = new ThreadLocal<Long>();  
    private final AtomicLong numTasks = new AtomicLong();  
    private final AtomicLong totalTime = new AtomicLong();  
  
    protected void beforeExecute(Thread t, Runnable r) {  
        super.beforeExecute(t, r);  
        System.out.println(String.format("Thread %s: start %s", t, r));  
        startTime.set(System.nanoTime());  
    }  
  
    protected void afterExecute(Runnable r, Throwable t) {  
        try {  
            long endTime = System.nanoTime();  
            long taskTime = endTime - startTime.get();  
            numTasks.incrementAndGet();  
            totalTime.addAndGet(taskTime);  
            System.out.println(String.format("Thread %s: end %s, time=%dns", t, r, taskTime));  
        } finally {  
            super.afterExecute(r, t);  
        }  
    }  
  
    protected void terminated() {  
        try {  
            System.out.println(String.format("Terminated: avg time=%dns", totalTime.get() / numTasks.get()));  
        } finally {  
            super.terminated();  
        }  
    }  
  
    private static class Task implements Runnable{  
  
        private String task;  
        public Task(String task){  
            this.task=task;  
        }  
          
        @Override  
        public void run() {  
            try {
                System.out.println(task);  
				Thread.sleep(2000);
	            if(task.equals("51")){  
	                throw new RuntimeException();  
	            } 
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
        }  
          
    }  
    public static void main(String[] args) throws Exception {  
        TimingThreadPool pool =  new TimingThreadPool(3, 4, 4, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3),  
                new ThreadPoolExecutor.CallerRunsPolicy());  
        
        for (int i = 0; i < 5; i++) {  
            try {  
                // 产生一个任务,并将其加入到线程池  
                String task = "" + i;  
                System.out.println("put " + task);  
                pool.execute(new Task(task));  
  
                // 便于观察,等待一段时间  
                Thread.sleep(500);  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
        Thread.sleep(5000);  
        pool.shutdown();  
        System.out.println(pool.getTaskCount()+"   c:"+pool.getCompletedTaskCount());  
    }  
} 
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值