package main
2
3 import "fmt"
4 import "time"
5
6 func main(){
7 ch := make(chan int, 5)
8 go func(){
9 for i := 0; i < 10; i++{
10 ch <- i
11 }
12 }()
13
14 go func(){
15 for {
16 a, ok := <- ch
17 if !ok{
18 fmt.Println("close")
21 return
22 }
23 fmt.Println("a:", a)
24 }
25 }()
26 fmt.Println("ok")
close(ch)
27 time.Sleep(time.Second)
28 }
输出结果:
ok
package main
2
3 import "fmt"
4 import "time"
5
6 func main(){
7 ch := make(chan int, 5)
8 go func(){
9 for i := 0; i < 10; i++{
10 ch <- i
11 }
12 }()
13
14 go func(){
15 for {
16 a, ok := <- ch
17 if !ok{
18 fmt.Println("close")
19
20 close(ch)
21 return
22 }
23 fmt.Println("a:", a)
24 }
25 }()
26 fmt.Println("ok")
27 time.Sleep(time.Second)
28 }
输出结果:
[root@localhost GoChatroom]# ./test
ok
a: 0
a: 1
a: 2
a: 3
a: 4
a: 5
a: 6
a: 7
a: 8
a: 9