【CountDownLatch实例】主线程等待其它线程执行完毕
来源:互联网 发布:东盟水果进口贸易数据 编辑:程序博客网 时间:2024/06/07 18:23
本文章主要体现2点:
1 主线程等待子线程执行完毕。通过CountDownLatch实现
2 演示共享的HashMap的put操作在多个线程中,如何同步。
这里主要是对比了synchronized块和Collections类的装饰功能。
======================================
如下面代码,主线程main,等待现场Thread1和2执行完毕,再打印数据。
注意:由于HashMap本身不是线程安全的,执行结果有时候会很奇怪,如Map的size是2,但只有一个数据。
异常结果如下:
thread already start, waiting...
map size is :2
map key is :2
解决办法是:在MapOper类中,对put进行类同步。
synchronized(this.getClass()){
}
注意,我注释了下面代码,因为他只能同步map引用的操作,而map传入到MapOper后,
map的地址被赋值给this.map了。所以下面的代码不生效。
Collections.synchronizedMap(map);
package multithread;import java.util.Collections;import java.util.HashMap;import java.util.Iterator;import java.util.concurrent.CountDownLatch;public class CountDownLatchForWaitSubThread {@SuppressWarnings("unchecked")public static void main(String[] args) throws InterruptedException {CountDownLatchForWaitSubThread test = new CountDownLatchForWaitSubThread();CountDownLatch latch = new CountDownLatch(2);HashMap map = new HashMap();//Collections.synchronizedMap(map);Thread t1 = new Thread(test.new MapOper(latch,map,1));Thread t2 = new Thread(test.new MapOper(latch,map,2));t1.start();t2.start();System.out.println("thread already start, waiting...");latch.await();for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {String key = (String) iterator.next();System.out.println("map size is :"+map.size());System.out.println("map key is :"+key);}}public class MapOper implements Runnable {CountDownLatch latch ;HashMap map;int i;public MapOper(CountDownLatch latch, HashMap map, int i) {this.latch = latch;this.map = map;this.i = i;}public void run() {synchronized (this.getClass()) {map.put(String.valueOf(i),i);}try {Thread.sleep(1);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}latch.countDown();}}}
阅读全文
0 0
- 【CountDownLatch实例】主线程等待其它线程执行完毕
- Java主线程等待子线程执行完毕-CountDownLatch
- Java主线程等待子线程执行完毕-CountDownLatch
- Java主线程等待子线程执行完毕-CountDownLatch
- 进阶篇:等待多个子线程完毕再执行主线程的方法之CountDownLatch(十二)
- 主线程等待子线程执行完毕后再执行
- JAVA主线程等待子线程执行完毕再执行
- 主线程等待所有子线程执行完毕例子
- 主线程等待多个线程执行完毕
- 主线程等待所有子线程执行完毕例子
- Java多线程--主线程等待所有子线程执行完毕
- Java多线程--让主线程等待子线程执行完毕
- Java主线程等待所有子线程执行完毕再执行解决办法集
- Java主线程等待所有子线程执行完毕再执行解决办法
- Java主线程等待所有子线程执行完毕再执行解决办法集
- Java主线程等待所有子线程执行完毕再执行解决办法集
- java主线程等待所有子线程执行完毕在执行(常见面试题)
- java主线程等待所有子线程执行完毕在执行(常见面试题)
- react-native 轮播图 ——react-native-swiper使用
- C++学习:引用和函数的高级用法
- Mybatis--Statement Builders
- VMvare拷贝后提示路径错误(无法打开xxxx文件)
- lintcode-矩阵面积
- 【CountDownLatch实例】主线程等待其它线程执行完毕
- 生成1-256十进制,二进制,八进制,十六进制值
- JQuery
- c++ 解析从浏览器端传过来的图像base64编码,并转换成opencv识别的格式
- 今天第一天加入CSDN,发现CSDN网站的一个小BUG!
- Mybatis--Logging
- Hadoop在虾米音乐
- MFC防止绘图闪烁——双缓冲技术
- Mybatis--XML 映射配置文件