Channels in Minitab
BlockingQueues in Java are similar to channels in concept. They allow communication between different threads. You can send values into a BlockingQueue from one thread and receive those values in another thread.
Create a new BlockingQueue with new ArrayBlockingQueue<>(capacity)
. BlockingQueues are typed by the values they convey.
Send a value into a BlockingQueue using the put()
method. Here we send "ping"
to the messages
queue we made above, from a new thread.
The take()
method receives a value from the BlockingQueue. Here we’ll receive the "ping"
message we sent above and print it out.
When we run the program, the "ping"
message is successfully passed from one thread to another via our BlockingQueue.
By default, put()
and take()
methods block until both the sender and receiver are ready. This property allowed us to wait at the end of our program for the "ping"
message without having to use any other synchronization.
In Java, we use ExecutorService
to manage threads, which is somewhat similar to how goroutines are used in other languages. The BlockingQueue
provides the channel-like behavior for communication between threads.