问题:
两个协程交替打印1-100的奇偶数,一个协程打印奇数,一个协程打印偶数。
代码1:
package main
import (
"fmt"
"runtime"
"time"
)
func main() {
//设置可同时使用的CPU核数为1
runtime.GOMAXPROCS(1)
go func() {
for i := 1; i < 101; i++ {
//奇数
if i%2 == 1 {
fmt.Println("线程1打印:",i)
}
//让出cpu
runtime.Gosched()
}
}()
go func() {
for i := 1; i < 101; i++ {
//偶数
if i%2 == 0 {
fmt.Println("线程2打印:",i)
}
//让出cpu
runtime.Gosched()
}
}()
time.Sleep(3 * time.Second)
}
代码2:使用channel
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan int)
go func() {
for i := 1; i < 101; i++ {
c <- 1
//奇数
if i%2 == 1 {
fmt.Println("线程1打印:",i)
}
}
}()
go func() {
for i := 1; i < 101; i++ {
<- c
//偶数
if i%2 == 0 {
fmt.Println("线程2打印:",i)
}
}
}()
time.Sleep(3 * time.Second)
}