Go-select实现超时

Go-select实现超时

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "time"
 6 )
 7 
 8 func main() {
 9     ch := make(chan int)
10     quit := make(chan bool)
11 
12     //新开协程
13     go func() {
14         for {
15             select {
16             case num := <-ch:
17                 fmt.Println("num:", num)
18             case <-time.After(3 * time.Second):
19                 fmt.Println("超时")
20                 quit <- true
21             }
22         }
23     }()
24     for i := 0; i < 3; i++ {
25         ch <- i
26     }
27     <-quit
28     fmt.Println("程序结束")
29 }
View Code

 

posted @ 2019-05-29 22:50  大西瓜Paul  阅读(209)  评论(0编辑  收藏  举报
/*增加返回顶部按钮*/ 返回顶部 /*给标题增加蓝色背景长条*/