Go的并发Java示例 [英] Concurrency Java example of Go

查看:130
本文介绍了Go的并发Java示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下 GoByExamples 中的并发频道示例

Java中是否有相同的东西?

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


推荐答案

选择语句 在Go语言语法级别引入并发的原因。并发函数调用可以(并且通常可以)在库级别上使用助手函数(如 spawn(function()))来实现,并且像其他数据结构一样拥有互斥锁或锁语言。但选择语句不能。

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.

这篇关于Go的并发Java示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆