Channel Synchronization in Minitab
Java provides a different mechanism for concurrency compared to goroutines and channels. We’ll use threads and a CountDownLatch
to achieve similar functionality.
import java.util.concurrent.CountDownLatch;
public class ChannelSynchronization {
// This is the method we'll run in a separate thread. The
// CountDownLatch will be used to notify the main thread
// that this method's work is done.
public static void worker(CountDownLatch latch) {
System.out.print("working...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("done");
// Signal that we're done
latch.countDown();
}
public static void main(String[] args) throws InterruptedException {
// Create a CountDownLatch with a count of 1
CountDownLatch latch = new CountDownLatch(1);
// Start a worker thread, passing it the latch
new Thread(() -> worker(latch)).start();
// Block until we receive a notification from the
// worker thread via the latch
latch.await();
}
}
To run the program:
$ javac ChannelSynchronization.java
$ java ChannelSynchronization
working...done
In this Java version, we use a CountDownLatch
instead of a channel. The CountDownLatch
is initialized with a count of 1, and the worker thread calls countDown()
when it’s finished. The main thread waits on the latch with await()
, which blocks until the count reaches zero.
If you removed the latch.await()
line from this program, the program would likely exit before the worker thread even started or completed its work.
This example demonstrates how to use a CountDownLatch
for simple thread synchronization in Java. For more complex scenarios involving multiple threads, you might prefer to use other concurrent utilities provided by Java, such as ExecutorService
or CompletableFuture
.