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,该值就是当前时间






你可能感兴趣的:(go学习笔记)