ThreadPoolExecutor实现线程池

构造方法:
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,long keepAliveTime, TimeUnit unit,BlockingQueue<Runnable> workQueue,RejectedExecutionHandler handler)

参数解读:

corePoolSize: 线程池维护线程的最少数量

maximumPoolSize:线程池维护线程的最大数量

keepAliveTime: 线程池维护线程所允许的空闲时间

unit: 线程池维护线程所允许的空闲时间的单位

workQueue: 线程池所使用的缓冲队列

handler: 线程池对拒绝任务的处理策略

package com.threadPool;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MyThreadPool extends ThreadPoolExecutor {

    private static MyThreadPool myPool = new MyThreadPool(10, 100, 1,
            TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>());

    private MyThreadPool(int corePoolSize, int maximumPoolSize,
            long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    public static MyThreadPool getInstance() {
        return myPool;
    }
}


package com.threadPool;

import java.util.concurrent.CountDownLatch;

public class MainThread {
    public static void main(String[] args) {
        ThreadExecutor executor = new ThreadExecutor("A", 3);
        executor.execute();
    }
}

class ThreadExecutor {
    private String prefix;
    private int size;

    public ThreadExecutor(String prefix, int size) {
        this.prefix = prefix;
        this.size = size;
    }

    public void execute() {
        System.out.println(prefix + " begin.");
        ThreadA temp = null;
        CountDownLatch cDownLatch = new CountDownLatch(size);
        for (int i = 0; i < size; i++) {
            temp = new ThreadA(cDownLatch, prefix + i);
            MyThreadPool.getInstance().execute(temp);
        }
        try {
            cDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(prefix + " end.");
    }
}


package com.threadPool;

import java.util.concurrent.CountDownLatch;

public class ThreadA implements Runnable {

    private CountDownLatch cDownLatch;

    private String name;

    public ThreadA(CountDownLatch cDownLatch, String threadName) {
        this.cDownLatch = cDownLatch;
        this.name = threadName;
    }

    @Override
    public void run() {
        System.out.println(name + " begin.");
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name + " end.");
        cDownLatch.countDown();
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值