例子

package main

import (
    "fmt"
    "time"
)

var channel = make(chan int, 5)

func main() {
    go producer()

    // 遍历通道
    for i:= range channel {
        fmt.Printf("consume %d\n", i)
    }

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

func producer() {
    for i := 0; i <= 10; i++ {
        channel <- i
        fmt.Printf("produce %d\n", i)
    }

    // 关闭通道
    close(channel)
}

 

posted @ 2024-04-30 18:06  飞雪飘鸿  阅读(6)  评论(0编辑  收藏  举报
https://damo.alibaba.com/ https://tianchi.aliyun.com/course?spm=5176.21206777.J_3941670930.5.87dc17c9BZNvLL