Title here
Summary here
Channel synchronization in Java can be achieved using different mechanisms. In this example, we’ll use a CountDownLatch
to synchronize execution across threads. When waiting for multiple threads to finish, you may prefer to use an ExecutorService
with a Future
or CompletableFuture
.
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
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 {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("done");
// Count down to notify 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, giving it the latch to count down
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
If you removed the latch.await()
line from this program, the main thread would exit before the worker thread even started its work.
In this Java implementation:
CountDownLatch
instead of a channel to synchronize between threads.worker
method is defined as a static method that takes a CountDownLatch
as a parameter.main
method, we create a new thread to run the worker
method.latch.await()
to block the main thread until the worker thread completes its task.This approach achieves similar synchronization behavior to the original example, adapted to Java’s concurrency model.