Countdownlatch Usage---Wait for multiple threads to finish executing
Countdownlatch Usage---Wait for multiple threads to finish executing
Countdownlatch Usage---Wait for multiple threads to finish executing
Countdownlatch Usage---Wait for multiple threads to finish executing
I. Countdownlatch usage
The Countdownlatch class is located under the Java.util.concurrent package and can be used to implement similar counter functions. For example, there is a task a, which waits for the other 4 tasks to be executed before they can be executed, and this is done using Countdownlatch.
The Countdownlatch class provides only one constructor:
1 |
public CountDownLatch( int count) { }; //参数count为计数值 |
Then the following 3 methods are the most important methods in the Countdownlatch class:
123 |
public void await () throws interruptedexception {}; //the thread that calls the await () method is suspended, It waits until the count value is 0 to continue execution of public boolean Code class= "Java Plain" >await ( long timeout, Timeunit unit) throws interruptedexception {}; //is similar to await (), except that the count value has not changed to 0 after a certain amount of time and will continue to execute public void countdown () {}; //subtract the Count value by 1 |
Let's look at an example and see how Countdownlatch is used:
12345678910111213141516171819202122232425262728293031323334353637383940 |
public class Test {
public static void main(String[] args) {
final CountDownLatch latch =
new CountDownLatch(
2
);
new Thread(){
public void run() {
try {
System.out.println(
"子线程"
+Thread.currentThread().getName()+
"正在执行"
);
Thread.sleep(
3000
);
System.out.println(
"子线程"
+Thread.currentThread().getName()+
"执行完毕"
);
latch.countDown();
}
catch (InterruptedException e) {
e.printStackTrace();
}
};
}.start();
new Thread(){
public void run() {
try {
System.out.println(
"子线程"
+Thread.currentThread().getName()+
"正在执行"
);
Thread.sleep(
3000
);
System.out.println(
"子线程"
+Thread.currentThread().getName()+
"执行完毕"
);
latch.countDown();
}
catch (InterruptedException e) {
e.printStackTrace();
}
};
}.start();
try {
System.out.println(
"等待2个子线程执行完毕..."
);
latch.await();
System.out.println(
"2个子线程已经执行完毕"
);
System.out.println(
"继续执行主线程"
);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
Execution Result:
1234567 |
线程Thread- 0 正在执行 线程Thread- 1 正在执行 等待 2 个子线程执行完毕... 线程Thread- 0 执行完毕 线程Thread- 1 执行完毕 2 个子线程已经执行完毕 继续执行主线程 |
Countdownlatch Usage---Wait for multiple threads to finish executing