【CountDownLatch实例】主线程等待其它线程执行完毕

本文章主要体现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 block
				e.printStackTrace();
			}
			latch.countDown();
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值