2 回答

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超8個(gè)贊
解釋起來(lái)很簡(jiǎn)單。您SayGreetings
使用 go 關(guān)鍵字調(diào)用兩次,這會(huì)導(dǎo)致 SayGreetings 函數(shù)的兩次并發(fā)執(zhí)行。最后,您不必等到兩個(gè)功能都完成!您的代碼在調(diào)用兩個(gè)函數(shù)后只等待 2 秒,每個(gè)函數(shù)等待超過(guò)兩秒。所以你要么增加 main 的等待時(shí)間,要么等到兩個(gè)函數(shù)都完成

TA貢獻(xiàn)2041條經(jīng)驗(yàn) 獲得超4個(gè)贊
將睡眠時(shí)間增加到 time.Sleep(20 *time.Second)主要
package main
import (
"log"
"math/rand"
"time"
)
func SayGreetings(greeting string, times int) {
for i := 0; i < times; i++ {
log.Println(greeting)
d := time.Second * time.Duration(rand.Intn(5)) / 2
time.Sleep(d) // sleep for 0 to 2.5 seconds
}
}
func main() {
rand.Seed(time.Now).UnixNano())
log.SetFlags(0)
go SayGreetings("hi!", 10)
go SayGreetings("hello!", 10)
time.Sleep(20 * time.Second)
}
Output:
======
hi!
hi!
hello!
hello!
hi!
hello!
hi!
hello!
hello!
hi!
hello!
hi!
hi!
hello!
hello!
hello!
hi!
hello!
hi!
hi!
- 2 回答
- 0 關(guān)注
- 101 瀏覽
添加回答
舉報(bào)