on the go way (二)channel 的用法

在Go语言中channel的使用方法有很多,首先来看以下的使用方法

1)当作事件信号来用,当某一件事完成之后,通知另一件事的完成

    

package main

import "fmt"

func onedream(exit chan int){
for i:=0;i<10;i++{
fmt.Println("hello ",i)
}
exit<-0

}
func main(){
var wait =make(chan int)
go onedream(wait)

<-wait
fmt.Println("this goroutine over") 
close(wait) }
 1 package main
 2 import 
 3 (
 4  "fmt"
 5  "time"   
 6 )
 7 func onedream(start ,wait chan int ){
 8     fmt.Println("等待制造数据命令中....")
 9     <-start
10     fmt.Println("开始制造数据-----")
11     for i:=0;i<10;i++{
12         fmt.Println("hello world ",i)
13     }
14     wait<-0
15 }
16 func main(){
17     var start1=make(chan int)
18     var wait1=make(chan int)
19     go onedream(start1,wait1)
20     time.Sleep(time.Second*10)
21     fmt.Println("发命令开始造数据")
22     start1<-1
23     <-wait1
24     
25     fmt.Println("制造数据结束....")
26     close(start1)
27     close(wait1)
28 }

2)多个线程同时进行

 1 package main 
 2 import(
 3     "fmt"
 4 )
 5 func onedream(index int,exit chan int){
 6     fmt.Println("this is  my index ",index)
 7     exit<-index
 8 }
 9 func main(){
10     var flag=make(chan int ,10)
11     for i:=0;i<10;i++{
12        go onedream(i,flag)
13     }
14     
15     for i:=0;i<10;i++{
16         fmt.Println("back index is ",<-flag)
17     }
18     
19     close(flag)
20     
21 }

 

posted on 2016-03-22 14:01  AAAAAApple  阅读(394)  评论(0编辑  收藏  举报

导航