CountDownLatch学习

<pre code_snippet_id="569358" snippet_file_name="blog_20150417_1_1404918" name="code" class="java">CountDownLatch是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程的操作执行完后再执行
 
 
 
 
 
 
</pre><pre code_snippet_id="569358" snippet_file_name="blog_20150417_3_2248647" name="code" class="java">
package com.sgcc.uds.search.mq;

import java.util.concurrent.CountDownLatch;

/**
 * CountDownlatch,是一种Sychronizer,它可以延迟线程的进度直到线程的进度到线程到达终止状态。
 
它本身而言是Java并发包中非常有用的一个类,它可以让某些任务完成以后再继续运行下面的内容,
每个任务本身执行完毕后让计数器减一,直到计数器清零后,以下的内容才可以继续运行,否则将阻塞等待。
 
想了一下,这个场景非常适合用于项目中这样的场景: 我们有个项目,它需要三个第三方的API,
并把结果拿到,在一个线程中顺序去拿结果没有问题,但是这里这三个任务是非常耗时的操作,
如果顺序获取性能非常差,因此可以考虑用三个线程,当三个线程拿到结果后才继续主线程的工作,
等三个线程运行结束后,由主线程去取子线程运行的结果。 这里有个很重要的前提:我们的系统运行在4个cpu的server上,
这样多线程才能体现性能,JVM会分配这些线程尽量运行在不同的cpu上。
 * @author Administrator
 *
 */
public class CountDownLatchSample {
    
    public static void main(String[] args) {
        String[] strs = getResult();
        for (int i = 0; i < strs.length; i++) {
            System.out.println(strs[i]);
        }
        
    }
    
    public static String[] getResult(){
        String[] strs = new String[3];
        CountDownLatch countDownLatch = new CountDownLatch(3);
        Work1 work1 = new Work1(countDownLatch,strs[0]);
        Work2 work2 = new Work2(countDownLatch,strs[1]);
        Work3 work3 = new Work3(countDownLatch,strs[2]);
        work1.start();
        work2.start();
        work3.start();
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        strs[0] = work1.str1;
        strs[1] = work2.str2;
        strs[2] = work3.str3;
        return strs;
    }
}

class Work1 extends Thread{
    public String str1;
    public CountDownLatch latch1;
    public Work1(CountDownLatch latch1,String str1){
        this.latch1 = latch1;
        this.str1 = str1;
    }
    
    public void run(){
        str1="work1";
        latch1.countDown();
    }
}

class Work2 extends Thread{
    public String str2;
    public CountDownLatch latch2;
    public Work2(CountDownLatch latch2,String str2){
        this.latch2 = latch2;
        this.str2 = str2;
    }
    
    public void run(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        str2="work2";
        latch2.countDown();
    }
}

class Work3 extends Thread{
    public String str3;
    public CountDownLatch latch3;
    public Work3(CountDownLatch latch3,String str3){
        this.latch3 = latch3;
        this.str3 = str3;
    }
    
    public void run(){
        try {
			Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        str3="work3";
        latch3.countDown();
    }
}


package com.sgcc.uds.search.mq;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

public class CountDownLatchWorkerDemo {
	final static SimpleDateFormat sdf = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	public static void main(String[] args) throws InterruptedException {
		CountDownLatch latch = new CountDownLatch(2);// 两个工人的协作
		Worker worker1 = new Worker("zhang san", 5000, latch);
		Worker worker2 = new Worker("li si", 5000, latch);
		worker1.start();//
		worker2.start();//
		latch.await();// 等待所有工人完成工作
		System.out.println("all work done at " + sdf.format(new Date()));
	}

	static class Worker extends Thread {
		String workerName;
		int workTime;
		CountDownLatch latch;

		public Worker(String workerName, int workTime, CountDownLatch latch) {
			this.workerName = workerName;
			this.workTime = workTime;
			this.latch = latch;
		}

		public void run() {
			System.out.println("Worker " + workerName + " do work begin at "
					+ sdf.format(new Date()));
			doWork();// 工作了
			System.out.println("Worker " + workerName + " do work complete at "
					+ sdf.format(new Date()));
			latch.countDown();// 工人完成工作,计数器减一
		}

		private void doWork() {
			try {
				Thread.sleep(workTime);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}

package com.sgcc.uds.search.mq;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * 
 * @author Administrator
 *该程序用来模拟发送命令与执行命令,主线程代表指挥官,新建3个线程代表战士,战士一直等待着指挥官下达命令,
 *若指挥官没有下达命令,则战士们都必须等待。一旦命令下达,战士们都去执行自己的任务,指挥官处于等待状态,
 *战士们任务执行完毕则报告给指挥官,指挥官则结束等待。
 */
public class CountdownLatchOrderTest {

    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool(); //创建一个线程池
        final CountDownLatch cdOrder = new CountDownLatch(1);//指挥官的命令,设置为1,指挥官一下达命令,则cutDown,变为0,战士们执行任务
        final CountDownLatch cdAnswer = new CountDownLatch(3);//因为有三个战士,所以初始值为3,每一个战士执行任务完毕则cutDown一次,当三个都执行完毕,变为0,则指挥官停止等待。        
        for(int i=0;i<3;i++){
            Runnable runnable = new Runnable(){
                    public void run(){
                    try {
                        System.out.println("线程" + Thread.currentThread().getName() + 
                                "正准备接受命令");                        
                        cdOrder.await(); //战士们都处于等待命令状态
                        System.out.println("线程" + Thread.currentThread().getName() + 
                        "已接受命令");                                
                        Thread.sleep((long)(Math.random()*10000));    
                        System.out.println("线程" + Thread.currentThread().getName() + 
                                "回应命令处理结果");                        
                        cdAnswer.countDown(); //任务执行完毕,返回给指挥官,cdAnswer减1。                    
                    } catch (Exception e) {
                        e.printStackTrace();
                    }                
                }
            };
            service.execute(runnable);//为线程池添加任务
        }        
        try {
            Thread.sleep((long)(Math.random()*10000));
        
            System.out.println("线程" + Thread.currentThread().getName() + 
                    "即将发布命令");                        
            cdOrder.countDown(); //发送命令,cdOrder减1,处于等待的战士们停止等待转去执行任务。
            System.out.println("线程" + Thread.currentThread().getName() + 
            "已发送命令,正在等待结果");    
            cdAnswer.await(); //命令发送后指挥官处于等待状态,一旦cdAnswer为0时停止等待继续往下执行
            System.out.println("线程" + Thread.currentThread().getName() + 
            "已收到所有响应结果");    
        } catch (Exception e) {
            e.printStackTrace();
        }                
        service.shutdown(); //任务结束,停止线程池的所有线程

    }
}

package com.sgcc.uds.search.mq;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// 一个CountDouwnLatch实例是不能重复使用的,也就是说它是一次性的,
//锁一经被打开就不能再关闭使用了,如果想重复使用,请考虑使用CyclicBarrier。
public class CountDownLatch100Test {

    // 模拟了100米赛跑,10名选手已经准备就绪,只等裁判一声令下。当所有人都到达终点时,比赛结束。
    public static void main(String[] args) throws InterruptedException {

        // 开始的倒数锁 
        final CountDownLatch begin = new CountDownLatch(1);  

        // 结束的倒数锁 
        final CountDownLatch end = new CountDownLatch(10);  

        // 十名选手 
        final ExecutorService exec = Executors.newFixedThreadPool(10);  

        for (int index = 0; index < 10; index++) {
            final int NO = index + 1;  
            Runnable run = new Runnable() {
                public void run() {  
                    try {  
                        // 如果当前计数为零,则此方法立即返回。
                        // 等待
                        begin.await();  
                        Thread.sleep((long) (Math.random() * 10000));  
                        System.out.println("No." + NO + " arrived");  
                    } catch (InterruptedException e) {  
                    } finally {  
                        // 每个选手到达终点时,end就减一
                        end.countDown();
                    }  
                }  
            };  
            exec.submit(run);
        }  
        System.out.println("Game Start");  
        // begin减一,开始游戏
        begin.countDown();  
        // 等待end变为0,即所有选手到达终点
        end.await();  
        System.out.println("Game Over");  
        exec.shutdown();  
    }
}



你可能感兴趣的:(CountDownLatch学习)