使用CountDownLatch循环打印十次ABC
使用CountDownLatch循环打印十次ABC
使用CountDownLatch循环打印十次ABC## 标题
最近遇到一个使用三个线程顺序打印ABC,连续打印十次的问题,关于这个问题网上解决方案很多,但是我发现网上却没有CountDownLatch的解决方案。
首先大概一下CountDownLatch,
CountDownLatch有await()和countDown()两个方法,每次调用countDown()方法时count会减一,调用await()方法只要count不为0则会一直阻塞。
废话不说,上代码:
public class ThreadPrint {
private static Map<String, CountDownLatch> countDownLatchMap = Maps.newHashMap();
private static ExecutorService threadPoolExecutor = new ThreadPoolExecutor(3, 3, 2,
TimeUnit.SECONDS, new LinkedBlockingQueue(20),
Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardPolicy());
/*** 1、定义dependLatch(所依赖的latch名)、selfLatch(自己的latch名)和word(需要打印的)* 2、首先调用所依赖的latch的await()方法,如果所依赖的latch的count为0,则重置所依赖的latch并打印需要输出的,最后将自身的count减去* 3、sum为需要执行的次数*/
private static class MyThread implements Runnable {private String dependLatch;private String selfLatch;private String word;private MyThread(String dependLatch, String selfLatch, String word) {this.dependLatch = dependLatch;this.selfLatch = selfLatch;this.word = word;}@Overridepublic void run() {int sum = 10;int parameter = 1;for (int i = 0; i < sum; i++) {try {countDownLatchMap.get(dependLatch).await();countDownLatchMap.put(dependLatch, new CountDownLatch(parameter));System.out.print(Thread.currentThread().getId() + ":" + word + "\n");countDownLatchMap.get(selfLatch).countDown();} catch (InterruptedException e) {e.printStackTrace();}}}
}public static void main(String[] args) {String latchA = "A";String latchB = "B";String latchC = "C";int parameter = 1;countDownLatchMap.put(latchA, new CountDownLatch(parameter));countDownLatchMap.put(latchB, new CountDownLatch(parameter));countDownLatchMap.put(latchC, new CountDownLatch(parameter));//latchC阻塞了latchA,先让latchC为0,则A执行MyThread threadA = new MyThread(latchC, latchA,latchA);threadPoolExecutor.execute(threadA);MyThread threadB = new MyThread(latchA, latchB,latchB);threadPoolExecutor.execute(threadB);MyThread threadC = new MyThread(latchB, latchC,latchC);threadPoolExecutor.execute(threadC);//调用latchC的countDown()方法,使latchA先运行countDownLatchMap.get(latchC).countDown();threadPoolExecutor.shutdown();
}
}
最新文章
- python len ljust
- Oracle中rowid的用法(全面)
- Platform Builder
- vmware装的ubuntu的界面怎么全屏?
- 非诚勿扰php男嘉宾,非诚勿扰 php
- dump文件的创建及使用
- skipped: maximum number of running instances reached (1)
- skip connections
- 给陌生的你听
- 芯片的本质是什么?(4)物质与数字世界接口
- Jmeter——BeanShell PreProcessor的用法
- c语言return 0和return 1的区别
- js“弹出对话框”和“弹出窗口”详解
- Python爬虫抓取网页图片
- 在window下查看占用tomcat进程,杀死进程并启用tomcat
- 计算机软件可以用虚拟串口吗,虚拟串口以及在Proteus中的使用
- Qt QSqlQueryModel详解