【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
原创粉丝点击