ExecutorService(线程池)

package Thread;

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

/**
 * @author 犀角
 * @date 2019/11/1 16:13
 * @description 执行器:创建了一个固定的线程池,该线程池包含了两个线程。然后使用线程池执行4个任务。因此,4个任务共享线程池中的两个线程。完成任务后,关闭线程池,程序结束
 */
public class SimpExc {
    public static void main(String[] args) {
        CountDownLatch cd1 = new CountDownLatch(5);
        CountDownLatch cd2 = new CountDownLatch(5);
        CountDownLatch cd3 = new CountDownLatch(5);
        CountDownLatch cd4 = new CountDownLatch(5);
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        System.out.println("Starting");

        //Start the Threads.
        executorService.execute(new MyThread(cd1,"A"));
        executorService.execute(new MyThread(cd2,"B"));
        executorService.execute(new MyThread(cd3,"C"));
        executorService.execute(new MyThread(cd4,"D"));

        try {
            cd1.await();
            cd2.await();
            cd3.await();
            cd4.await();
        } catch (InterruptedException e) {
            System.out.println(e);
        }
        executorService.shutdown();
        System.out.println("Done");
    }

}
class MyThread implements Runnable{
    String name;
    CountDownLatch latch;

    MyThread(CountDownLatch c,String n){
        latch = c;
        name = n;

        new Thread(this);
    }

    @Override
    public void run() {
        for (int i = 0;i <5;i++){
            System.out.println(name + ":" +i);
            latch.countDown();
        }
    }
}

 线程池构造方法:

ThreadPoolExecutor(int corePoolSize, // 1
                              int maximumPoolSize,  // 2
                              long keepAliveTime,  // 3
                              TimeUnit unit,  // 4
                              BlockingQueue<Runnable> workQueue, // 5
                              ThreadFactory threadFactory,  // 6
                              RejectedExecutionHandler handler ) { //7

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值