Go基础语法练习(3)


package main

import (
    "fmt"
    "strconv"
    "time"
)

func display() {
    for i := 0; i < 10; i++ {
        fmt.Println("协程display", i)
        time.Sleep(1 * time.Second)
        //if i == 3 {
        //  // 退出当前的协程
        //  // runtime.Goexit()
        //  // 结束程序
        //  //os.Exit(-1)
        //  // 返回当前函数
        //  return
        //}
    }
}

func main() {
    go display()
    go chanTest()
    selectTest()
    for i := 0; i < 10; i++ {
        fmt.Println("协程main", i)
        time.Sleep(1 * time.Second)
    }
    time.Sleep(10 * time.Second)
}

func chanTest() {
    // 创建传输整数的管道
    numChan := make(chan int)
    defer close(numChan)
    strChan := make(chan string)
    defer close(strChan)
    go func() {
        count := 1
        for data := range numChan {
            // 读取管道中的数据
            strChan <- "s" + strconv.Itoa(count)
            count++
            fmt.Println("data:", data)
            time.Sleep(1 * time.Second)
        }
    }()
    for i := 0; i < 50; i++ {
        // 将数据写入管道
        numChan <- i
        fmt.Println("go main,writer", i)
        fmt.Println("strChan:", <-strChan)
        time.Sleep(1 * time.Second)
    }
}

func selectTest() {
    ch1 := make(chan int)
    ch2 := make(chan int)
    ch3 := make(chan int)
    quit := make(chan bool)

    //新开一个协程
    go func() {
        for {
            time.Sleep(1 * time.Second)
            select {
            case num := <-ch1:
                fmt.Println("num1 = ", num)
            case num := <-ch2:
                fmt.Println("num2 = ", num)
            case num := <-ch3:
                fmt.Println("num3 = ", num)
            case <-time.After(3 * time.Second):
                fmt.Println("超时")
                quit <- true
            }
        }
    }() //别忘了()
    for i := 0; i < 6; i++ {
        ch1 <- i
        ch3 <- i
        ch2 <- i
        time.Sleep(time.Second)
    }
    if <-quit {
        fmt.Println("程序结束")
    }
}