为什么这不会打印出 20 条问候语?

我正在学习 Golang,我正在努力理解为什么即使我调用该函数两次,每次调用 10 次,也没有打印出 20 条问候语。


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(2 * time.Second)

}


慕侠2389804
浏览 73回答 2
2回答

慕森卡

解释起来很简单。您SayGreetings使用 go 关键字调用两次,这会导致 SayGreetings 函数的两次并发执行。最后,您不必等到两个功能都完成!您的代码在调用两个函数后只等待 2 秒,每个函数等待超过两秒。所以你要么增加 main 的等待时间,要么等到两个函数都完成

缥缈止盈

将睡眠时间增加到 time.Sleep(20 *time.Second)主要package mainimport (&nbsp; &nbsp; "log"&nbsp; &nbsp; "math/rand"&nbsp; &nbsp; "time")func SayGreetings(greeting string, times int) {&nbsp; &nbsp; for i := 0; i < times; i++ {&nbsp; &nbsp; &nbsp; &nbsp; log.Println(greeting)&nbsp; &nbsp; &nbsp; &nbsp; d := time.Second * time.Duration(rand.Intn(5)) / 2&nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(d) // sleep for 0 to 2.5 seconds&nbsp; &nbsp; }}func main() {&nbsp; &nbsp; rand.Seed(time.Now).UnixNano())&nbsp; &nbsp; log.SetFlags(0)&nbsp; &nbsp; go SayGreetings("hi!", 10)&nbsp; &nbsp; go SayGreetings("hello!", 10)&nbsp; &nbsp; 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!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go