1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| // 一次性定时器 func test1() { var ch chan int var ch1 chan int ch = make(chan int, 10) ch1 = make(chan int, 10) go func() { for i := 0; i < 10; i++ { ch <- i ch1 <- i * i time.Sleep(time.Second) } }()
for { select { case v := <-ch: fmt.Printf("ch:%d\n", v) case v := <-ch1: fmt.Printf("ch1:%d\n", v) // 设置超时时间为1秒 不建议使用After 容易造成内存泄漏 case t := <-time.After(time.Second): fmt.Println("get data time out:", t) } } }
func test2() { var ch chan int var ch1 chan int ch = make(chan int, 10) ch1 = make(chan int, 10) go func() { for i := 0; i < 10; i++ { ch <- i ch1 <- i * i time.Sleep(time.Second) } }()
for { t := time.NewTicker(time.Second) select { case v := <-ch: fmt.Printf("ch:%d\n", v) case v := <-ch1: fmt.Printf("ch1:%d\n", v) // 设置超时时间为1秒 推荐使用 case t := <-t.C: fmt.Println("get data time out:", t) } // 使用完手动关闭 t.Stop() } }
func main() { test2() }
|