golang学习笔记——select

select就是用来监听和channel有关的IO操作,当 IO 操作发生时,触发相应的动作

package main
 
import (
    "fmt"
    "time"
)
 
func main() {
    ch := make(chan int)
    o := make(chan bool)
 
    go func() {
         for {
                 select {
                 case <-time.After(3 * time.Second):
                         fmt.Println("超时")
                         o <- true
                 case num := <-ch:
                         fmt.Println(num)
                 }
         }
    }()
 
    <-o
}

 

posted @ 2021-03-05 20:57  GPHPER  阅读(70)  评论(0编辑  收藏  举报
TOP