Skip to content

Commit

Permalink
add the countdownlatch
Browse files Browse the repository at this point in the history
  • Loading branch information
guangxush committed Jun 25, 2024
1 parent ed2fb4e commit 04152cc
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 2 deletions.
4 changes: 2 additions & 2 deletions HappyParse/src/main/java/GenerateFileByDate.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ public static void main(String[] args) {
GenerateFileByDate date = new GenerateFileByDate();
long prefix = Long.valueOf(getTodayYearMonthDay());
System.out.println(prefix);
prefix = 20240701;
while (prefix <= 20240731) {
prefix = 20250301;
while (prefix <= 20250331) {
createFile(prefix + ".md");
prefix++;
}
Expand Down
61 changes: 61 additions & 0 deletions HighAvailable/src/main/java/CountDownLatchExec.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
* 并发执行
*
* @author: guangxush
* @create: 2024/06/25
*/
public class CountDownLatchExec {

public static ThreadPoolExecutor executor = new ThreadPoolExecutor(
2,
2,
1,
TimeUnit.MICROSECONDS,
new ArrayBlockingQueue<Runnable>(2));

public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(2);
Runnable task1 = () ->{
try {
System.out.println("task1 exec start....");
Thread.sleep(3L);
System.out.println("task1 exec end....");
}catch (InterruptedException exception){
System.out.println("task1 exec error....");
}finally {
latch.countDown();
}
};

Runnable task2 = () ->{
try {
System.out.println("task2 exec start....");
Thread.sleep(2L);
System.out.println("task2 exec end....");
}catch (InterruptedException exception){
System.out.println("task2 exec error....");
}finally {
latch.countDown();
}
};

// 线程池提交任务
executor.execute(task1);
executor.execute(task2);

// 并发获取结果
try{
boolean await = latch.await(2L, TimeUnit.SECONDS);
if(await){
System.out.println("exec success!");
}
}catch (InterruptedException exception){
System.out.println("exec error!");
}
}
}

0 comments on commit 04152cc

Please sign in to comment.