golang-select与协程

小试牛刀
package main

import (
	"fmt"
	"time"
)

func main() {
	// 小试牛刀
	start := time.Now()
	ch1 := make(chan interface{})
	ch2 := make(chan string)
	ch3 := make(chan string)
	go func() {
		fmt.Println("服务员来了。。。")
		time.Sleep(4 * time.Second)
		close(ch1)
	}()
	go func() {
		fmt.Println("我点了一份炒米饭。。。")
		time.Sleep(3 * time.Second)
		ch2 <- "炒米饭"
	}()
	go func() {
		fmt.Println("你点了一份炒烙饼。。。")
		time.Sleep(3 * time.Second)
		ch3 <- "炒烙饼"
	}()
	fmt.Println("刚进饭店,等待服务员。。。。。。")
	select {
	case <-ch1:
		fmt.Printf("后厨正在做,用时%v\n", time.Since(start))
	case data := <-ch2:
		fmt.Printf("%v做好了,用时%v\n", data, time.Since(start))
	case data := <-ch3:
		fmt.Printf("%v做好了,用时%v\n", data, time.Since(start))
	// default:
	// 	fmt.Printf("还没做好呢,再等等吧\n")
	}

	fmt.Println()

	// select赋值顺序 从上到下,从左到右
	ch4 := make(chan string, 1)
	ch5 := make(chan string, 1)
	chs := []chan string{ch4, ch5}
	names := []string{"过得刚好", "人间烟火"}
	select {
	case getChan(0, chs) <- getName(0, names):
		fmt.Println("执行了第一条语句")
	case getChan(1, chs) <- getName(1, names):
		fmt.Println("执行了第二条语句")
	default:
		fmt.Println("默认")
	}

	fmt.Println()

	// break只会退出select,不会退出for循环
	ch := make(chan string)
	go func() {
		for {
			ch <- "商业的底层逻辑"
		}
	}()
	for {
		select {
		case data := <-ch:
			fmt.Println(data)
			// break
			goto exit
		}
		time.Sleep(3 * time.Second)
		fmt.Println("循环中。。。")
	}
exit:
	fmt.Println("退出循环")
	fmt.Println("main结束")
}

func getName(i int, names []string) string {
	fmt.Printf("names:%d\n", i)
	return names[i]
}

func getChan(i int, chs []chan string) chan string {
	fmt.Printf("chs:%d;", i)
	return chs[i]
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值