1、未使用go channel
package main import ( "fmt" "time" ) func printer(s string) { for _, v := range s { fmt.Println(string(v)) time.Sleep(time.Millisecond * 3000) } } func person() { printer("hello") } func person2() { printer("world") } func main() { go person() go person2() for { } }
d:\goprojects\src\day1\练习>go run main.go h w e o l r l l o d exit status 2
2、使用channel
package main import ( "fmt" "time" ) var ch = make(chan int, 1) func printer(s string) { for _, v := range s { fmt.Println(string(v)) time.Sleep(time.Millisecond * 3000) } } func person() { printer("hello") ch <- 1 } func person2() { <-ch printer("world") } func main() { go person() go person2() for { } }
d:\goprojects\src\day1\练习>go run main.go h e l l o w o r l d
3、小结
channel 有两端,一端写入(数据传入)ch<- ;一端读出(传出数据);要求读写两端必须同时满足条件,才能在channel上完成数据流动,否则阻塞。