1、使用两个goroutine交替、顺序打印一段字符串的字符
输入:hello world
输出:hello world
关键点:控制goroutine的执行先后循序
golang语言版本:
package main
import (
"fmt"
"sync"
)
func main() {
content := "hello world"
var wg sync.WaitGroup //打印完后再退出主goroutine
var count = len(content)
wg.Add(count)
ch1 := make(chan string, 1)
ch2 := make(chan string, 1)
ch1 <- "1"
for _, v := range content {
select { //监听并选择有值的通道进行处理
case <-ch1:
go func(s string) {
defer wg.Done()
fmt.Println(s)
ch2 <- "2"
}(string(v))
case <-ch2:
go func(s string) {
defer wg.Done()
fmt.Println(s)
ch1 <- "1"
}(string(v))
}
}
wg.Wait()
}
输出: