ExecutorService(线程池)

mac2025-09-12  10

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)