go 通过select实现超时

package main

import (
    "fmt"
    "time"
)

func main()  {
    ch := make(chan int)
    quit := make(chan bool)

    go func() {
        for{
            select {
                  case num := <-ch:
                      fmt.Println("num=",num)
                     case <-time.After(3*time.Second):
                         fmt.Println("超时")
                          quit <- true
                          //break
            }
        }
    }()

    for i:= 0;i<5;i++{
        ch <- i
        time.Sleep(time.Second)
    }
    qt:= <-quit
    fmt.Println("程序结束:qt=",qt)


}

猜你喜欢

转载自www.cnblogs.com/dqh123/p/12075357.html