在 goroutine 中通过 sleep 等待主线程

agy*_*eya -1 sleep channel go

编写这个非常基本的代码来理解通道。

  1. 如果一个 Goroutine 中有等待,为什么主 Goroutine 还要等待它呢?我读到主 Goroutine 需要有一个等待时间,因为在调用 Goroutine 后控制权会立即传回给它。

  2. 为什么goroutine不像java中的主线程和子线程那样设计可以并行运行?

func main() {
    channel := make(chan int)
    go func() {
        time.Sleep(3*time.Second)
    }()

    for {
        fmt.Println("../");
        <-channel
    }
}
Run Code Online (Sandbox Code Playgroud)

Roe*_*rel 5

我认为你的主线程正在等待来自通道的东西

func main() {
    channel := make(chan int)
    go func() {
        time.Sleep(3*time.Second)
        channel <- 1 // Sending something to the channel to let the main thread continue
        channel <- 2
    }()

    for {
        fmt.Println("../");
        <-channel // Waiting for something to come from the channel
    }
}
Run Code Online (Sandbox Code Playgroud)

关于您的具体问题:

如果一个 Goroutine 中有等待,为什么主 Goroutine 还要等待它呢?

它不会等待,它可能在频道上等待。

我读到主 Goroutine 需要有一个等待时间,因为在调用 Goroutine 后控制权会立即传回给它。

如果您的主程序没有在通道上等待(或在无限循环中堆栈),那么它已经完成并关闭了应用程序。GoRoutines 与主线程一起关闭(如 Java 守护线程)

为什么goroutine不像java中的主线程和子线程那样设计可以并行运行?

他们实际上是这样做的(: