Go 的并发 Java 示例

我有以下来自GoByExamples的并发通道示例


Java中是否有等价的东西?我原以为实现同样的事情会更加冗长。


// Basic sends and receives on channels are blocking.

// However, we can use `select` with a `default` clause to

// implement _non-blocking_ sends, receives, and even

// non-blocking multi-way `select`s.


package main


import "fmt"


func main() {

    messages := make(chan string)

    signals := make(chan bool)


    // Here's a non-blocking receive. If a value is

    // available on `messages` then `select` will take

    // the `<-messages` `case` with that value. If not

    // it will immediately take the `default` case.

    select {

    case msg := <-messages:

        fmt.Println("received message", msg)

    default:

        fmt.Println("no message received")

    }


    // A non-blocking send works similarly.

    msg := "hi"

    select {

    case messages <- msg:

        fmt.Println("sent message", msg)

    default:

        fmt.Println("no message sent")

    }


    // We can use multiple `case`s above the `default`

    // clause to implement a multi-way non-blocking

    // select. Here we attempt non-blocking receives

    // on both `messages` and `signals`.

    select {

    case msg := <-messages:

        fmt.Println("received message", msg)

    case sig := <-signals:

        fmt.Println("received signal", sig)

    default:

        fmt.Println("no activity")

    }

}



梦里花落0921
浏览 135回答 1
1回答

杨魅力

Select语句是在 Go 语言语法级别引入并发的原因。并发函数调用可以(并且通常完成)在库级别使用辅助函数spawn( function())和通道实现,就像大多数其他语言中具有互斥锁或锁的数据结构一样。但select声明不能。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go