题目:使用两个goroutine交替打印序列,一个goroutine打印数字,一个打印字母,最终效果如下:12AB34CD56EF78GH910IJ
package main
import (
"fmt"
"runtime"
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
chan_n := make(chan bool)
chan_c := make(chan bool,1)
done := make(chan struct{})
go func() {
for i := 1; i<11; i+=2{
<- chan_c //2 阻塞, 1解除2的阻塞,5解除2的阻塞
fmt.Print(i) //输出
fmt.Print(i+1)//输出
chan_n <- true // 4阻塞
}
}()
go func() {
char_seq := []string{"A","B","C","D","E","F","G","H","I","J","K"}
for i:=0;i<10;i+=2{
<-chan_n //3 阻塞 ,4解除3的阻塞
fmt.Print(char_seq[i]) //输出
fmt.Print(char_seq[i+1])//输出
chan_c <- true //5 阻塞
}
done <- struct{}{}
}()
chan_c <- true //1 阻塞
<- done
}
本文由 Ryan 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为:
2019/03/08 17:02