golang

时间:2025-03-03 15:05:55

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  if the timer is no longer needed.
func After(d Duration) <-chan Time {
	return NewTimer(d).C
}

根据注释可知,在等待给定的一段时间后,向返回值发送当前时间,返回值是一个单向只读通道

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

}

运行发现,在等待五秒钟后,打印

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

3.分析:

第一个case中,通道c一直处于阻塞状态;第二个case中,在()结束后,从返回值通道中取出一个值赋予了d,该值就是当前时间