2.3四种线程连接池的配置和使用(和自定义线程池)

四种线程连接池的配置和使用

最终调用类和方法
{参数有 核心线程数目,最大线程数目,存活时间(当前线程执行完这个任务之后,等待下一个任务到来的最长等待时间。如果在这个时间内没有新的任务来到,那当前线程就会退出),时间单位,等待队列(用于存放待执行的任务)}

public ThreadPoolExecutor(
// 核心线程数目
int corePoolSize,
//最大线程数目
int maximumPoolSize,
//存活时间(当前线程执行完这个任务之后,等待下一个任务到来的最长等待时间。如果在这个时间内没有新的任务来到,那当前线程就会退出)
long keepAliveTime,
//时间单位
TimeUnit unit,
//等待队列(用于存放待执行的任务)
BlockingQueue<Runnable> workQueue,
//线程工厂
ThreadFactory threadFactory,
//处理异常
RejectedExecutionHandler handler){
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler);}

比较重要的几个类:
ExecutorService: 真正的线程池接口。
ScheduledExecutorService: 能和Timer/TimerTask类似,解决那些需要任务重复执行的问题。
ThreadPoolExecutor: ExecutorService的默认实现。
ScheduledThreadPoolExecutor: 继承ThreadPoolExecutor的ScheduledExecutorService接口实现,周期性任务调度的类实现

1.newSingleThreadExecutor

/**
 * @Auther: cpb
 * @Date: 2018/11/12 15:41
 * @Description:
 */
public class Solution {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
//        MyThread  myThread = new MyThread();
//        A1Thread thread = new A1Thread(myThread);
//        for(int i = 0 ; i < 5;i++){
//            //执行线程
//            executorService.submit(thread);
//        }
//        //结束线程
//        executorService.shutdown();



        MyCallable myCallable = new MyCallable();
        for (int i = 0 ; i<5 ;i++){
            Future<Integer> future = executorService.submit(myCallable);
            try {
                System.out.println(future.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        executorService.shutdown();

    }
    static class MyThread implements Runnable{
        public void run() {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Hello");
        }
    }

    static class MyCallable implements Callable<Integer> {
        private int i;
        public Integer call() throws Exception {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return i++;
        }
    }
}

2.newFixedThreadPool

import java.util.concurrent.*;

/**
 * @Auther: cpb
 * @Date: 2018/11/12 15:41
 * @Description:
 */
public class Solution {
    public static void main(String[] args) {
    ExecutorService executorService = Executors.newFixedThreadPool(5);
    MyThread  myThread = new MyThread();
    for(int i = 0 ; i < 10;i++){
        Thread thread = new Thread(myThread);
        //执行线程
        executorService.submit(thread);
    }
    //结束线程
    executorService.shutdown();



//    MyCallable myCallable = new MyCallable();
//    for (int i = 0 ; i<10 ;i++){
//        Future<Integer> future = executorService.submit(myCallable);
//        try {
//            System.out.println(future.get());
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } catch (ExecutionException e) {
//            e.printStackTrace();
//        }
//    }
//    executorService.shutdown();

}
    static class MyThread implements Runnable{
        public void run() {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
            System.out.println("Hello");
        }
    }

    static class MyCallable implements Callable<Integer> {
        private int i;
        public Integer call() throws Exception {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
            return i++;
        }
    }
}

3.newCachedThreadPool

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


/**
 * @Auther: cpb
 * @Date: 2018/11/12 15:41
 * @Description:
 */
public class Solution {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        MyThread  myThread = new MyThread();
        for(int i = 0 ; i < 10;i++){
            Thread thread = new Thread(myThread);
            //执行线程
            executorService.submit(thread);
        }
        //结束线程
        executorService.shutdown();



    //    MyCallable myCallable = new MyCallable();
    //    for (int i = 0 ; i<10 ;i++){
    //        Future<Integer> future = executorService.submit(myCallable);
    //        try {
    //            System.out.println(future.get());
    //        } catch (InterruptedException e) {
    //            e.printStackTrace();
    //        } catch (ExecutionException e) {
    //            e.printStackTrace();
    //        }
    //    }
    //    executorService.shutdown();

    }
    static class MyThread implements Runnable{
        public void run() {
            try {
                //测试时间60秒 ,有点长啊
                Thread.sleep(60000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
            System.out.println("Hello");
        }
    }

    static class MyCallable implements Callable<Integer> {
        private int i;
        public Integer call() throws Exception {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
            return i++;
        }
    }

}

4.newScheduledThreadPool

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

/**
 * @Auther: cpb
 * @Date: 2018/11/12 15:41
 * @Description:
 */
public class Solution {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newScheduledThreadPool(5);
        MyThread  myThread = new MyThread();
        for(int i = 0 ; i < 10;i++){
            Thread thread = new Thread(myThread);
            //执行线程
            executorService.submit(thread);
        }
        //结束线程
        executorService.shutdown();



        //    MyCallable myCallable = new MyCallable();
        //    for (int i = 0 ; i<10 ;i++){
        //        Future<Integer> future = executorService.submit(myCallable);
        //        try {
        //            System.out.println(future.get());
        //        } catch (InterruptedException e) {
        //            e.printStackTrace();
        //        } catch (ExecutionException e) {
        //            e.printStackTrace();
        //        }
        //    }
        //    executorService.shutdown();

    }
    static class MyThread implements Runnable{
        public void run() {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"  :Hello");
        }
    }

    static class MyCallable implements Callable<Integer> {
        private int i;
        public Integer call() throws Exception {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
            return i++;
        }
    }
}

5.自定义线程池

线程池类

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Auther: cpb
 * @Date: 2018/11/12 17:10
 * @Description:
 */
public class MyThreadPool extends ThreadPoolExecutor {

    private static final AtomicInteger atomicInteger = new AtomicInteger(0);

    public MyThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
    }

    public MyThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit,null,null,null);
    }

    /**
     * 任务执行,以原子方式将当前值加 1
     */
    public void execute(Runnable task) {
        atomicInteger.getAndIncrement();
        super.execute(task);
    }

}

执行类

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: cpb
 * @Date: 2018/11/12 17:01
 * @Description:
 */
public class Solution {
    public static void main(String[] args) {
        ExecutorService executorService = new MyThreadPool(5,10,60, TimeUnit.SECONDS);
        MyThread  myThread = new MyThread();
        for(int i = 0 ; i < 10;i++){
            Thread thread = new Thread(myThread);
            //执行线程
            executorService.submit(thread);
        }
        //结束线程
        executorService.shutdown();



        //    MyCallable myCallable = new MyCallable();
        //    for (int i = 0 ; i<10 ;i++){
        //        Future<Integer> future = executorService.submit(myCallable);
        //        try {
        //            System.out.println(future.get());
        //        } catch (InterruptedException e) {
        //            e.printStackTrace();
        //        } catch (ExecutionException e) {
        //            e.printStackTrace();
        //        }
        //    }
        //    executorService.shutdown();
    }

    static class MyThread implements Runnable{
        public void run() {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"  :Hello");
        }
    }

    static class MyCallable implements Callable<Integer> {
        private int i;
        public Integer call() throws Exception {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
            return i++;
        }
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值