07-携程-02-携程通讯

2021-11-21  本文已影响0人  玄德公笔记

1. 示例说明

1.1 逻辑

两个携程:

1.2 代码结构

image.png

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
上一篇下一篇

猜你喜欢

热点阅读