这段代码为什么能按照顺序输出 而且隔一秒输出一个
如果睡眠改成 time.Sleep(time.Second * time.Duration(rand.Intn(4)))
就更奇怪了 前几个输出是隔两三秒输出, 后面几个一起输出
```go
package main
import (
"fmt"
"log"
"runtime"
"strconv"
"strings"
"time"
)
var ch = make(chan int)
func task(i int) {
time.Sleep(time.Second)
log.Println("task...", i, "go id:", GoID())
<-ch
}
func GoID() int {
var buf [64]byte
n := runtime.Stack(buf[:], false)
idField := strings.Fields(strings.TrimPrefix(string(buf[:n]), "goroutine "))[0]
id, err := strconv.Atoi(idField)
if err != nil {
panic(fmt.Sprintf("cannot get goroutine id: %v", err))
}
return id
}
func main() {
for i := 0; i < 10; i++ {
go task(i)
ch <- i
}
fmt.Println("over")
}
```
有疑问加站长微信联系(非本文作者)