方式一

使用 sync.WaitGroup

package main

import (
	"fmt"
	"math/rand"
	"strconv"
	"sync"
	"time"
)

func main() {
	workerNum := 10
	var wg sync.WaitGroup
	wg.Add(workerNum)
	for i := 0; i < workerNum; i++ {
		go worker(i, "Name"+strconv.FormatInt(int64(i), 10), &wg)
	}
	wg.Wait()
}

func worker(id int, hello string, wg *sync.WaitGroup) {
	time.Sleep(time.Second * time.Duration(rand.Int31n(10)))
	fmt.Printf("workerID = %v, Hello %v\n", id, hello)
	wg.Done()
}

输出的结果:

[Running] go run "/Users/emacsist/go-project/src/main.go"
workerID = 5, Hello Name5
workerID = 8, Hello Name8
workerID = 1, Hello Name1
workerID = 2, Hello Name2
workerID = 4, Hello Name4
workerID = 7, Hello Name7
workerID = 0, Hello Name0
workerID = 3, Hello Name3
workerID = 6, Hello Name6
workerID = 9, Hello Name9

[Done] exited with code=0 in 9.214 seconds

方法二

package main

import (
	"fmt"
	"math/rand"
	"strconv"
	"time"
)

func main() {
	workerNum := 10
	result := make(chan int, workerNum)
	for i := 0; i < workerNum; i++ {
		go worker(i, "Name"+strconv.FormatInt(int64(i), 10), result)
	}
	for i := 0; i < workerNum; i++ {
		fmt.Printf("workerID = %v is finished.\n", <-result)
	}
}

func worker(id int, hello string, result chan int) {
	time.Sleep(time.Second * time.Duration(rand.Int31n(10)))
	fmt.Printf("workerID = %v, Hello %v\n", id, hello)
	result <- id
}

输出的结果类似如下:

[Running] go run "/Users/emacsist/go-project/src/main.go"
workerID = 4, Hello Name4
workerID = 4 is finished.
workerID = 5, Hello Name5
workerID = 5 is finished.
workerID = 1, Hello Name1
workerID = 0, Hello Name0
workerID = 1 is finished.
workerID = 0 is finished.
workerID = 7, Hello Name7
workerID = 7 is finished.
workerID = 8, Hello Name8
workerID = 8 is finished.
workerID = 3, Hello Name3
workerID = 9, Hello Name9
workerID = 3 is finished.
workerID = 9 is finished.
workerID = 6, Hello Name6
workerID = 6 is finished.
workerID = 2, Hello Name2
workerID = 2 is finished.

[Done] exited with code=0 in 9.251 seconds