Golang交替打印奇偶数

package main

import (
	"fmt"
	"sync"
)

var wg sync.WaitGroup

func main() {
	evenCh, oddCh := make(chan bool, 1), make(chan bool, 1)
	defer close(evenCh)
	defer close(oddCh)

	wg = sync.WaitGroup{}
	wg.Add(1)

	go printNumbersSequentially(1, 10, oddCh, evenCh)

	evenCh <- true

	wg.Wait()
}

// 合并后的打印方法
func printNumbersSequentially(start, end int, oddCh, evenCh chan bool) {
	for i := start; i <= end; i++ {
		if i%2 == 0 { // 偶数
			<-oddCh
			fmt.Println(i)
			evenCh <- true
		} else { // 奇数
			<-evenCh
			fmt.Println(i)
			oddCh <- true
		}
	}

	wg.Done()
}

posted @ 2024-04-15 11:23  朝阳1  阅读(44)  评论(0编辑  收藏  举报