027_go语言中的通道选择器

代码演示

package main

import "fmt"
import "time"

func main() {
	c1 := make(chan string)
	c2 := make(chan string)
	go func() {
		time.Sleep(time.Second * 1)
		c1 <- "one"
	}()
	go func() {
		time.Sleep(time.Second * 2)
		c2 <- "two"
	}()
	for i := 0; i < 2; i++ {
		select {
		case msg1 := <-c1:
			fmt.Println("received", msg1)
		case msg2 := <-c2:
			fmt.Println("received", msg2)
		}
	}
}

  

代码运行结果

received one
received two

  

代码解读

  • go语言的通道选择器(select)可以同时等待多个通道操作
  • 以上例子就是利用关键字select同时等待创建的两个通道的值
  • 对于select语句而言,它会不断的检测通道是否有值传过来,一旦发现传过来,立刻获取并输出
posted @ 2018-04-11 22:48  Joestar  阅读(274)  评论(0编辑  收藏  举报