Go算法题:交替按顺序打印数字

2024-02-19 16:45:07 浏览数 (1)

代码语言:go复制
package main

import (
	"fmt"
	"time"
)

func main() {
	ch1 := make(chan struct{})
	ch2 := make(chan struct{})
	ch3 := make(chan struct{})

	go func() {
		for i := 1; i <= 100; i  = 3 {
			<-ch1
			fmt.Println(i)
			ch2 <- struct{}{}
		}
	}()

	go func() {
		for i := 2; i <= 100; i  = 3 {
			<-ch2
			fmt.Println(i)
			ch3 <- struct{}{}
		}
	}()

	go func() {
		for i := 3; i <= 100; i  = 3 {
			<-ch3
			fmt.Println(i)
			ch1 <- struct{}{}
		}
	}()

	ch1 <- struct{}{}

	time.Sleep(time.Second * 5)
}
go

0 人点赞