初始化Go学习项目
This commit is contained in:
34
go-select-practice/select_basic.go
Normal file
34
go-select-practice/select_basic.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
ch1 := make(chan string)
|
||||
ch2 := make(chan string)
|
||||
|
||||
// 模拟两个不同来源的“数据源”
|
||||
go func() {
|
||||
time.Sleep(1 * time.Second)
|
||||
ch1 <- "result from ch1 (1s)"
|
||||
}()
|
||||
|
||||
go func() {
|
||||
time.Sleep(2 * time.Second)
|
||||
ch2 <- "result from ch2 (2s)"
|
||||
}()
|
||||
|
||||
fmt.Println("等待 ch1 或 ch2 的结果...(谁先来处理谁)")
|
||||
|
||||
select {
|
||||
case v := <-ch1:
|
||||
fmt.Println("收到 ch1:", v)
|
||||
case v := <-ch2:
|
||||
fmt.Println("收到 ch2:", v)
|
||||
}
|
||||
|
||||
fmt.Println("main 结束")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user