企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
> # 交替打印 - 方式一 ~~~ package main import ( "fmt" "time" ) var i = 0 func main() { go A() go B() time.Sleep(time.Second * 60) } func A() { for { if i%2 == 0 { fmt.Println("a") i++ time.Sleep(time.Second) } } } func B() { for { if i%2 == 1 { fmt.Println("b") i++ time.Sleep(time.Second) } } } ~~~ - 方式二 ~~~ package main import ( "fmt" "time" ) func main() { ch1 := make(chan struct{}) ch2 := make(chan struct{}) go func() { for { <-ch1 fmt.Println("a") time.Sleep(time.Second) ch2 <- struct{}{} } }() go func() { for { <-ch2 fmt.Println("b") time.Sleep(time.Second) ch1 <- struct{}{} } }() ch1 <- struct{}{} time.Sleep(time.Second * 60) } ~~~