golang并发例子

前端之家收集整理的这篇文章主要介绍了golang并发例子前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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

猜你在找的Go相关文章