java多线程学习笔记-创建线程池的四种方式

一、newCachedThreadPool()可缓存线程池

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
 * @author yjf
 * @Description:TODO
 * @date 2018年4月5日下午3:38:51
 */
public class CachedThreadPool {
    public static void main(String[] args) {
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            final int index = i;
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            cachedThreadPool.execute(new Runnable() {
                public void run() {
                    System.out.println(index);
                }
            });
        }
    }
}

二、newFixedThreadPool()定长线程池

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
 * @author yjf
 * @Description:TODO
 * @date 2018年4月5日下午3:39:50
 */
public class FixedThreadPool {
    public static void main(String[] args) {  
        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(10);  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                }  
            });  
        }  
    }
}

三、newScheduledThreadPool()定长线程池

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 创建一个定长线程池,支持定时及周期性任务执行。
 * @author yjf
 * @Description:TODO
 * @date 2018年4月5日下午3:40:16
 */
public class ScheduledThreadPool {
    public static void main(String[] args) {  
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);  
        for (int i = 0; i < 10; i++) {  
            scheduledThreadPool.schedule(new Runnable() {  
                public void run() {  
                    System.out.println("delay 3 seconds");  
                }  
            }, 3, TimeUnit.SECONDS);  
        }  
  
    } 
}

四、newSingleThreadExecutor()单线程话的线程池

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
 * @author yjf
 * @Description:TODO
 * @date 2018年4月5日下午3:41:59
 */
public class SingleThreadExecutor {
     public static void main(String[] args) {  
            ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();  
            for (int i = 0; i < 10; i++) {  
                final int index = i;  
                singleThreadExecutor.execute(new Runnable() {  
                    public void run() {  
    /*                  System.out.println(index);*/  
                        try {  
                            System.out.println(index);  
                            Thread.sleep(2000);  
                        } catch (InterruptedException e) {  
                            e.printStackTrace();  
                        }  
                    }  
                });  
            }  
        }
}

五、单例FixedThreadPool线程池的构建

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
 * 单例FixedThreadPool线程池的构建
 * @author yjf
 * @Description:TODO
 * @date 2018年8月21日上午10:20:06
 */
public class ThreadManager {
    private static ThreadPool mThreadPool;

    // 获取单例的线程池对象
    public static ThreadPool getThreadPool() {
        if (mThreadPool == null) {
            synchronized (ThreadManager.class) {
                if (mThreadPool == null) {
                    int cpuNum = Runtime.getRuntime().availableProcessors();// 获取处理器数量
                    int threadNum = cpuNum * 2 + 1;// 根据cpu数量,计算出合理的线程并发数
                    mThreadPool = new ThreadPool(threadNum, threadNum, 0L);
                }
            }
        }
        return mThreadPool;
    }

    public static class ThreadPool {

        private ThreadPoolExecutor mexecutor;
        private int corepoolsize;
        private int maximumpoolsize;
        private long keepalivetime;

        private ThreadPool(int corepoolsize, int maximumpoolsize, long keepalivetime){
            this.corepoolsize = corepoolsize;
            this.maximumpoolsize = maximumpoolsize;
            this.keepalivetime = keepalivetime;
        }

        public void executor(Runnable runnable){

            if (runnable == null){
                return;
            }
            if (mexecutor == null){
                mexecutor = new ThreadPoolExecutor(corepoolsize, //核心线程数
                        maximumpoolsize, //最大线程数
                        keepalivetime, //闲置线程存活时间
                        TimeUnit.MILLISECONDS, // 时间单位
                        new LinkedBlockingDeque<Runnable>(), //线程队列
                        Executors.defaultThreadFactory(), //线程工厂
                        new ThreadPoolExecutor.AbortPolicy() //队列已满,而且当前线程数已经超过最大线程数时的异常处理策略
                );
            }
            mexecutor.execute(runnable);
        }

        public void cancel(Runnable runnable){
            if(mexecutor != null){
                mexecutor.getQueue().remove(runnable);
            }
        }

    }
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值