02-携程通讯

1. 代码结构

在这里插入图片描述

2. gorotine.go

不写sleep的话,goland还没有输出程序就结束了。

package gorotine

import (
	"fmt"
	"time"
)

//定义两个chanel
var chanInt chan int = make(chan int,10)
var timeOut chan bool = make(chan bool)

//定义一个函数向通道 发送数据
func Send()  {
	time.Sleep(time.Second * 1)
	chanInt <- 1
	time.Sleep(time.Second * 1)
	chanInt <- 2
	time.Sleep(time.Second * 1)
	chanInt <- 3
	time.Sleep(time.Second * 2)
	timeOut <- true
}
//第一一个函数从chanel读取数据
func Receive() {
	for{
		select {
		case num := <- chanInt:
			fmt.Println("NUM",num)
		case <- timeOut:
			fmt.Println("timeout......")

		}
	}
}

3. main.go

package main

import (
	"814/gorotine"
	"time"
)
func main () {
	go gorotine.Send()
	go gorotine.Receive()
	time.Sleep(time.Second * 60)
}

4. 执行结果

NUM 1
NUM 2
NUM 3
timeout......

Process finished with the exit code 0

posted on 2021-08-18 23:24  运维开发玄德公  阅读(8)  评论(0编辑  收藏  举报  来源

导航