标签:
package main import ( "fmt" "math/rand" "time" ) func main() { fmt.Println("start") chn := make(chan int, 5) rand.Seed(time.Now().UnixNano()) for i := 0; i < 5; i++ { x := rand.Intn(5) fmt.Println("i is", i, "rand is:", x) go worker(i, x, chn) } fmt.Println("end") for i := 0; i < 5; i++ { j := <-chn fmt.Println(j) } } func worker(i int, sleepInt int, chn chan int) { d := time.Duration(sleepInt) * time.Second time.Sleep(d) fmt.Println("I am ", i) j := i + 10 chn <- j }
go run 输出:
start
i is 0 rand is: 2
i is 1 rand is: 0
i is 2 rand is: 4
i is 3 rand is: 1
i is 4 rand is: 3
end
I am 1
11
I am 3
13
I am 0
10
I am 4
14
I am 2
12
标签:
原文地址:http://my.oschina.net/coseyo/blog/393885