在 goroutine 中等待主线程睡眠

Wait on main thread with sleep in goroutine

编写这段非常基本的代码来理解频道。

  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
    }
}

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

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
    }
}

关于您的具体问题:

If there is a wait in a goroutine, why is the main goroutine waiting on it?

它没有等待,它可能正在等待频道。

I read that the main goroutine needs to have a wait time as the control is passed back to it immediately after invoking goroutine.

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

Why are goroutines not designed like main thread and child threads in java where they can run in parallel?

他们确实这样做了 (: