Channels in Java
In Java, we don’t have built-in channels like in Go, but we can use BlockingQueue
to achieve similar functionality. BlockingQueue
is part of Java’s concurrent collections and provides thread-safe operations for adding and removing elements.
Here’s how the code works:
We create a
BlockingQueue<String>
calledmessages
. This queue will hold our messages.We start a new thread using
new Thread(() -> {...}).start()
. This is similar to using a goroutine in Go. Inside this thread, we put the string “ping” into the queue usingmessages.put("ping")
.In the main thread, we use
messages.take()
to receive a message from the queue. This operation will block until a message is available, similar to receiving from a channel in Go.Finally, we print the received message.
When we run the program, the “ping” message is successfully passed from one thread to another via our blocking queue.
By default, put
and take
operations on a BlockingQueue
block until they can be completed. This property allowed us to wait at the end of our program for the “ping” message without having to use any other synchronization mechanism.
While Java’s BlockingQueue
isn’t exactly the same as Go’s channels, it provides a similar way to safely communicate between concurrent threads.