The goroutine scheduler is not preemptive.

go - Why is time.sleep required to run certain goroutines? - Stack Overflow https://stackoverflow.com/questions/15771232/why-is-time-sleep-required-to-run-certain-goroutines

package main

import (
//"time"
"fmt"
)

func say(s string) {
for i := 0; i < 5; i++ {
// time.Sleep(100 * time.Microsecond)
fmt.Println(s)
}
}

func main() {
go say("world")
say("hello")
}


hello
hello
hello
hello
hello


package main

import (
"time"
"fmt"
)

func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Microsecond)
fmt.Println(s)
}
}

func main() {
go say("world")
say("hello")
}


输出结果不定

hello
world
hello
world
hello
world
world
hello
world
hello


hello
world
hello
world
world
hello
world
hello
hello


world
hello
world
hello
hello
world
hello
world
world
hello

原文地址:https://www.cnblogs.com/rsapaper/p/9641021.html