英文:
Concurrency Java example of Go
问题
我有以下并发通道的示例来自GoByExamples
在Java中有类似的东西吗?我原以为实现相同功能会更冗长。
// 基本的通道发送和接收是阻塞的。
// 但是,我们可以使用select
和default
子句来实现非阻塞的发送、接收,甚至是非阻塞的多路选择。
package main
import "fmt"
func main() {
messages := make(chan string)
signals := make(chan bool)
// 这是一个非阻塞的接收。如果`messages`上有值,
// `select`将使用该值接收`<-messages`的`case`。如果没有,
// 它将立即执行`default`的`case`。
select {
case msg := <-messages:
fmt.Println("received message", msg)
default:
fmt.Println("no message received")
}
// 非阻塞的发送类似。
msg := "hi"
select {
case messages <- msg:
fmt.Println("sent message", msg)
default:
fmt.Println("no message sent")
}
// 我们可以在`default`子句上方使用多个`case`
// 来实现多路非阻塞选择。这里我们尝试在`messages`和`signals`上进行非阻塞接收。
select {
case msg := <-messages:
fmt.Println("received message", msg)
case sig := <-signals:
fmt.Println("received signal", sig)
default:
fmt.Println("no activity")
}
}
英文:
I have below example of concurrency channels from GoByExamples
Is there something equivalent in Java? I would have thought it would be much more verbose to implement the same thing.
// 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")
}
}
答案1
得分: 0
select
语句是在Go语言中引入并发的原因。并发函数调用通常可以在库级别上使用辅助函数(如spawn(function())
)和通道来实现,就像大多数其他语言中的数据结构与互斥锁或锁一样。但是select
语句不能这样做。
英文:
Select
statement is the reason to introduce concurrency at language syntax level in Go. Concurrent function call can (and usually done) be implemented on library level with helper function like spawn( function())
and channels just as data structures with mutex or lock in most other languages. But select
statement can't.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论