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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章