`

java CountDownLatch 实例

阅读更多

一个线程等待

 

CountDownLatch使用其await()等待其他线程完成(使用减值为0来判断是否完成)。

是一个线程等待多个线程(1-N)的锁工具。

 

以下为实例代码:

 

package com.common;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class CountdownLatchTest extends Thread {

	public final int countThd = 10;
	public CountDownLatch latch = new CountDownLatch(countThd);
	
	public static void main(String[] args)
	{
		CountdownLatchTest one = new CountdownLatchTest();
		one.start();
		System.out.println("^^^^^^^^mainmianmian^^^^^^^^^");
	}
	
	public void run()
	{
		synchronized (this) {
			try {
				System.out.println("GoGoGoGoGoGoGoTOWork");
				//Executor executor = Executors.newCachedThreadPool();
				for(int i=0;i<this.countThd;i++)
				{
					ChildrenThread childt = new ChildrenThread(this.latch,i);
					Thread each = new Thread(childt);
					each.start();
					//executor.execute(childt);
				}
				latch.await();
				System.out.println("GoGoGoGoGoGoGoHomeNow");
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		//workForever();
	}
	public void workForever()
	{
		
		
	}
	
	class ChildrenThread implements Runnable
	{
		CountDownLatch latch;
		int num;
		public ChildrenThread(CountDownLatch latch,int num)
		{
			this.latch = latch;
			this.num = num;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				System.out.println("**********have a rest  "+num);
				Thread.sleep(1000);
				System.out.println("----------go back to work  "+num);
				latch.countDown();
				//CountdownLatchTest.this.latch.countDown();
				//System.out.println("%%%%%%%%%%I want to go home");
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
}

 讲述的是一个实习小弟只能等其他员工都改完活才能回家的故事 ,Yes,he is me.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics