package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
newRandStream := func(done <-chan interface{}) <-chan int {
randStream := make(chan int)
go func() {
defer fmt.Println("randstream closeed, exited!")
defer close(randStream)
for {
select {
case randStream <- rand.Int():
case <-done:
return
}
}
}()
return randStream
}
done := make(chan interface{})
randStream := newRandStream(done)
fmt.Println("Read 3 rand ints: ")
for i := 1; i <= 3; i++ {
fmt.Printf("%d %d \n", i, <-randStream)
}
close(done)
time.Sleep(1 * time.Second)
}
程序输出如下,
有疑问加站长微信联系(非本文作者)