码迷,mamicode.com
首页 > 其他好文 > 详细

golang并发例子

时间:2015-03-31 11:01:51      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:

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

golang并发例子

标签:

原文地址:http://my.oschina.net/coseyo/blog/393885

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!