CountDownLatch线程同步辅助

http://bughope.iteye.com/blog/2081935

在上一篇文章中写道用一个静态的变量保存线程的执行状态,并用时间等待的方法后来仔细考虑,其实是

线程不安全的.多个线程同时执行这个类时,这个静态变量的值就不能保证了.

用一个线程同步的Map保存这个值,勉强能实现[每个线程生产一个不重复的map的key]

但是这样很麻烦.

java. util. concurrent.CountDownLatch 

却能完美的实现.能线程安全的计数,因为每个实现的主线程在并发的情况下java.util.concurrent.CountDownLatch; 是新的实例 不会像上一篇一样需要处理计数器的线程安全.

具体代码如下

package org.masque.effective;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
 * 
 * @author [email protected]
 *
 */
public class ThreadTest {

	public static void main(String[] args) throws InterruptedException {
		CountDownLatch latch=new CountDownLatch(3);//数量标示线程的个数
		(new Thread1(latch)).start();
		(new Thread2(latch)).start();
		(new Thread3(latch)).start();
		latch.await();//等待线程执行完成.还有一个重载的方法可以设置超时时间
		System.out.println("over!");
	}
}

class Thread1 extends Thread{
	
	CountDownLatch latch;
	
	public Thread1(CountDownLatch latch){
		this.latch = latch;
	}
	
	@Override
	public void run() {
		for (int i=10;i<20;i++) {
			System.out.println("Thread1===========:"+i);
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		latch.countDown();//完成后计数
	}
}

class Thread2 extends Thread{
	
	CountDownLatch latch;
	
	public Thread2(CountDownLatch latch){
		this.latch = latch;
	}
	
	@Override
	public void run() {
		for (int i=10;i<20;i++) {
			System.out.println("Thread2===========:"+i);
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		latch.countDown();//完成后计数
	}
}

class Thread3 extends Thread{
	
	CountDownLatch latch;
	
	public Thread3(CountDownLatch latch){
		this.latch = latch;
	}
	
	@Override
	public void run() {
		for (int i=10;i<20;i++) {
			System.out.println("Thread3===========:"+i);
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		latch.countDown();//完成后计数
	}
}

 

你可能感兴趣的:(thread,线程,同步,线程安全,CountDownLatch)