Go语言通道问题
package main
import (
"fmt"
"time"
)
func sender(c chan string) {
t := time.NewTicker(1 * time.Second)
for {
c <- "I am sending a message"
<-t.C
}
}
func main() {
massage := make(chan string)
stop := make(chan bool)
go sender(massage)
go func() {
time.NewTicker(2 * time.Second)
fmt.Println("Time is up!")
stop <- true
}()
for {
select {
case <-stop:
fmt.Println("退出")
return
case msg := <-massage:
fmt.Println(msg)
}
}
}
“time is up”最先输出说明已经对stop传递true了那为什么程序没有结束
这种多线程操作谁先谁后不好说。有两个子线程和主线程同时运行。你没有用什么机制保证顺序执行