package cm.pool;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.ScheduledFuture;import java.util.concurrent.TimeUnit;public class test { public static Integer num = 20; public static Integer i = 0; public static void main(String[] args) { /** * 四种jdk中多线程的创建 */ /* * Executors.newSingleThreadExecutor().shutdown(); * Executors.newCachedThreadPool(); * Executors.newScheduledThreadPool(1); * Executors.newFixedThreadPool(2); */ final CountDownLatch countDownLatch = new CountDownLatch(2); // java内置线程池 ExecutorService executorService = Executors.newFixedThreadPool(2); executorService.submit(new Runnable() { @Override public synchronized void run() { while (test.num > 0) { test.num--; test.i++; System.out.println(Thread.currentThread().getName() + ":" + test.num); } countDownLatch.countDown(); } }); executorService.submit(new Runnable() { @Override public synchronized void run() { while (test.num > 0) { test.num--; test.i++; System.out.println(Thread.currentThread().getName() + ":" + test.num); } countDownLatch.countDown(); } }); executorService.submit(new Runnable() { @Override public void run() { try { countDownLatch.await(); System.out.println("统计线程1和线程2的执行次数:" + test.i); } catch (InterruptedException e) { e.printStackTrace(); } } }); executorService.shutdown(); Temp temp = new Temp(); final ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(10); /** * temp:线程任务 * 5:初始化时间 * 1:5秒后每1秒执行一次线程任务 TimeUnit.SECONDS:单位 */ ScheduledFuture scFuture = scheduled.scheduleWithFixedDelay(/**temp*/new Runnable() { int r=0; @Override public synchronized void run() { if(r==10){ scheduled.shutdown(); }else{ r++; System.out.println("10个线程计数:"+Thread.currentThread().getName()+":"+r); } } }, 5, 1, TimeUnit.SECONDS); }}
运行结果如下:
pool-1-thread-1:19pool-1-thread-1:18pool-1-thread-1:17pool-1-thread-1:16pool-1-thread-1:15pool-1-thread-1:14pool-1-thread-1:13pool-1-thread-1:12pool-1-thread-1:11pool-1-thread-1:10pool-1-thread-1:9pool-1-thread-1:7pool-1-thread-1:6pool-1-thread-1:5pool-1-thread-1:4pool-1-thread-1:3pool-1-thread-1:2pool-1-thread-1:1pool-1-thread-1:0pool-1-thread-2:6统计线程1和线程2的执行次数:2010个线程计数:pool-2-thread-1:110个线程计数:pool-2-thread-1:210个线程计数:pool-2-thread-2:310个线程计数:pool-2-thread-1:410个线程计数:pool-2-thread-3:510个线程计数:pool-2-thread-2:610个线程计数:pool-2-thread-4:710个线程计数:pool-2-thread-1:810个线程计数:pool-2-thread-5:910个线程计数:pool-2-thread-3:10
1.newFixedThreadPool的使用。
2.开启了两个线程池pool1、pool2
3.通过countDownLatch保证递减结果完成之后输出。
4.newScheduledThreadPool的使用