如何在Java中实现Go的非缓冲通道?

huangapple go评论203阅读模式
英文:

How would I implement Go's unbuffered channels in Java?

问题

Go提供了无缓冲和有缓冲的通道来在goroutine(线程)之间进行通信。在Java中,实现有界缓冲的缓冲通道是很直接的。

Go的无缓冲通道要求一个goroutine在另一个goroutine接收时发送数据。有人可以解释一下如何在Java中实现这个吗?

英文:

Go offers both unbuffered and buffered channels for communication among goroutines (threads). It is straightforward to implement buffered channels as bounded buffers in Java.

Go's unbuffered channels require one goroutine to be sending when the other goroutine is receiving. Can anyone explain to me how to implement that in Java?

答案1

得分: 1

在Java中,你可以使用SynchronousQueue,Java 8的源代码在这里:

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/concurrent/SynchronousQueue.java?av=f

英文:

In Java you can use a SynchronousQueue, the source for Java 8 is here

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/concurrent/SynchronousQueue.java?av=f

答案2

得分: 0

我建议你也看一下JCSP库。有关JCSP的更多详细信息,请参阅这个答案

很遗憾,Java没有与Goroutines等效的东西(曾经有过“绿色线程”,但已经被废弃)。因此,如果你使用线程,一旦线程数量变得有趣(例如超过一万个),你将承受沉重的内存占用。每个Java线程都需要一个操作系统线程和一个大的堆栈空间。

英文:

I suggest you also look into the JCSP library. There are further details of JCSP in this answer.

Java does not have anything that is equivalent to Goroutines, alas. (Once, there were 'Green Threads' long ago, but they were abandoned). So if you use threads instead, you will endure a heavy memory footprint as soon as the number of threads starts getting interesting (e.g. more than ten thousand). Every Java thread requires an operating system thread and a large stack space.

huangapple
  • 本文由 发表于 2017年4月25日 03:28:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/43596253.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定