package main
import (
"fmt"
"time"
)
func main() {
// 创建三个通道
ch1 := make(chan int)
ch2 := make(chan int)
ch3 := make(chan int)
// 模拟不同的goroutine向通道发送数据
go func() {
time.Sleep(2 * time.Second)
ch1 <- 10
}()
go func() {
time.Sleep(3 * time.Second)
ch2 <- 20
}()
go func() {
time.Sleep(1 * time.Second)
ch3 <- 30
}()
// 使用select语句接收数据并处理超时
select {
case data := <-ch1:
fmt.Println("Received from ch1:", data)
case data := <-ch2:
fmt.Println("Received from ch2:", data)
case data := <-ch3:
fmt.Println("Received from ch3:", data)
case <-time.After(2 * time.Second):
fmt.Println("Timeout occurred")
}
}
逻辑解释
- 通道创建:首先创建了三个不同的通道
ch1
、ch2
和 ch3
,用于接收数据。
- 模拟发送数据:使用三个匿名的goroutine分别向这三个通道发送数据,每个goroutine的发送时间不同,模拟不同的发送节奏。
- select语句:
select
语句可以监听多个通道的操作(发送或接收)。在这个例子中,它监听 ch1
、ch2
、ch3
三个通道的接收操作以及一个超时操作。
- 超时设置:
time.After(2 * time.Second)
会返回一个通道,在2秒后向该通道发送一个值。如果在2秒内没有任何数据从 ch1
、ch2
、ch3
通道接收到,select
语句会执行 time.After
对应的分支,输出 “Timeout occurred”,表示超时。如果在2秒内有数据从任何一个通道接收到,就会执行对应的 case
分支,输出接收到的数据。