packagemain import( "fmt" "math/rand" "time" ) funcmain(){ fmt.Println("start") chn:=make(chanint,5) rand.Seed(time.Now().UnixNano()) fori:=0;i<5;i++{ x:=rand.Intn(5) fmt.Println("iis",i,"randis:",x) goworker(i,x,chn) } fmt.Println("end") fori:=0;i<5;i++{ j:=<-chn fmt.Println(j) } } funcworker(iint,sleepIntint,chnchanint){ d:=time.Duration(sleepInt)*time.Second time.Sleep(d) fmt.Println("Iam",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