golang time.After()

1.源碼分析:

// After waits for the duration to elapse and then sends the current time
// on the returned channel.
// It is equivalent to NewTimer(d).C.
// The underlying Timer is not recovered by the garbage collector
// until the timer fires. If efficiency is a concern, use NewTimer
// instead and call Timer.Stop if the timer is no longer needed.
func After(d Duration) <-chan Time {
	return NewTimer(d).C
}

根據註釋可知,在等待給定的一段時間後,向返回值發送當前時間,返回值是一個單向只讀通道

2.demo:

func main() {
	c := make(chan int, 1)
	select {
	case m := <-c:
		fmt.Println(m)
	case d := <-time.After(5 * time.Second):
		fmt.Println("time out")
		fmt.Println("current Time :", d)
	}

}

運行發現,在等待五秒鐘後,打印

time out
current Time : 2017-12-22 15:04:05.0462009 +0800 CST m=+5.004000001

3.分析:

第一個case中,通道c一直處於阻塞狀態;第二個case中,在time.After()結束後,從返回值通道中取出一個值賦予了d,該值就是當前時間






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章