最近遇到这样一个功能要求:假设现在有T1,T2,T3共3个线程,如何保证T4第4个线程在前3个线程执行完毕后再执行(jdk层面实现)?
实现方式:使用CountDownLatch
代码:
CountDownLatchExample.java
package com.ccr.common.thread.concurrent;
import com.ccr.common.practice.DesignPatterns.AbstractFactoryPattern.SamePackageClass;
import java.util.concurrent.CountDownLatch;
/**
* Created by Chengrui on 2015/7/29.
*/
public class CountDownLatchExample {
public static class ProcessThread implements Runnable{
String name;
CountDownLatch countDownLatch;
Long workDuration;
public ProcessThread(String name, CountDownLatch latch, long duration){
this.name = name;
this.countDownLatch = latch;
this.workDuration = duration;
}
@Override
public void run() {
try {
System.out.println(name + " Processing Something for " + workDuration/1000 + "Seconds");
Thread.sleep(workDuration);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + " complete its works");
//when task finished .. count down the latch count
//basically, this is the same as calling lock object notify(),and object here is CountDownLatch.
countDownLatch.countDown();
System.out.println("count value is:" + countDownLatch.getCount());
}
}
}
CountDownLatchTest.java
package com.ccr.common.thread.concurrent;
import java.util.concurrent.CountDownLatch;
/**
* Created by Chengrui on 2015/7/29.
*/
public class CountDownLatchTest {
public static void main(String[] args){
//parent thread create a CountDownLatch object
CountDownLatch latch = new CountDownLatch(3);
System.out.println("count value is:" + latch.getCount());
new Thread(new CountDownLatchExample.ProcessThread("WorkThread1", latch, 2000)).start();
new Thread(new CountDownLatchExample.ProcessThread("WorkThread2", latch, 6000)).start();
new Thread(new CountDownLatchExample.ProcessThread("WorkThread3", latch, 4000)).start();
System.out.println("waiting for children processes to complete...");
try {
latch.await();
System.out.println("At this time, the count value is already 0...");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("The first three WorkThread processes completed...");
System.out.println("Parent Thread or The following WorkThread go on to work...");
}
}
输出结果:
count value is:3
waiting for children processes to complete...
WorkThread1 Processing Something for 2Seconds
WorkThread2 Processing Something for 6Seconds
WorkThread3 Processing Something for 4Seconds
WorkThread1 complete its works
count value is:2
WorkThread3 complete its works
count value is:1
WorkThread2 complete its works
count value is:0
At this time, the count value is already 0...
The first three WorkThread processes completed...
Parent Thread or The following WorkThread go on to work...
附:CountDownLatch帮助文档: