英文:
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的源代码在这里:
英文:
In Java you can use a SynchronousQueue, the source for Java 8 is here
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论