Java 线程+并发 CountDownLatch

Golang 协程+并发 sync.WaitGroup

Java并发参考例子

  1. package com.eomchat.common.http;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4. import java.util.concurrent.CountDownLatch;
  5. import java.util.concurrent.ExecutorService;
  6. import java.util.concurrent.SynchronousQueue;
  7. import java.util.concurrent.ThreadPoolExecutor;
  8. import java.util.concurrent.TimeUnit;
  9. public class TaskMain {
  10. private static final ExecutorService threadPool = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 0, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
  11. public static void main(String[] args) {
  12. int task = 5;
  13. CountDownLatch latch = new CountDownLatch(task);
  14. for (int i = 0; i < task; i++) {
  15. threadPool.execute(new Task(latch, i));
  16. }
  17. try {
  18. latch.await();
  19. } catch (InterruptedException e) {
  20. e.printStackTrace();
  21. }
  22. System.out.println("exit");
  23. }
  24. public static class Task implements Runnable {
  25. private final CountDownLatch latch;
  26. private final int i;
  27. public Task(CountDownLatch latch, int i) {
  28. this.latch = latch;
  29. this.i = i;
  30. }
  31. @Override
  32. public void run() {
  33. try {
  34. String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
  35. System.out.printf("%s task i = %s\n", time, i);
  36. } finally {
  37. latch.countDown();
  38. }
  39. }
  40. }
  41. }

Golang并发参考例子

  1. package main
  2. import (
  3. "log"
  4. "sync"
  5. )
  6. func main() {
  7. wg := &sync.WaitGroup{}
  8. for i := 0; i < 5; i++ {
  9. wg.Add(1)
  10. go func(wg *sync.WaitGroup, i int) {
  11. defer wg.Done()
  12. // TODO 执行你的业务代码
  13. log.Printf("task i = %d", i)
  14. }(wg, i)
  15. }
  16. wg.Wait()
  17. log.Println("exit")
  18. }