Java 线程+并发 CountDownLatch
Golang 协程+并发 sync.WaitGroup
Java并发参考例子
package com.eomchat.common.http;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TaskMain {
private static final ExecutorService threadPool = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 0, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
public static void main(String[] args) {
int task = 5;
CountDownLatch latch = new CountDownLatch(task);
for (int i = 0; i < task; i++) {
threadPool.execute(new Task(latch, i));
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("exit");
}
public static class Task implements Runnable {
private final CountDownLatch latch;
private final int i;
public Task(CountDownLatch latch, int i) {
this.latch = latch;
this.i = i;
}
@Override
public void run() {
try {
String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
System.out.printf("%s task i = %s\n", time, i);
} finally {
latch.countDown();
}
}
}
}
Golang并发参考例子
package main
import (
"log"
"sync"
)
func main() {
wg := &sync.WaitGroup{}
for i := 0; i < 5; i++ {
wg.Add(1)
go func(wg *sync.WaitGroup, i int) {
defer wg.Done()
// TODO 执行你的业务代码
log.Printf("task i = %d", i)
}(wg, i)
}
wg.Wait()
log.Println("exit")
}