Channel Synchronization in Mercury

This example demonstrates how to use thread synchronization in Java to coordinate execution between multiple threads. While Java doesn’t have built-in channels like Go, we can achieve similar functionality using other concurrency primitives.

import java.util.concurrent.CountDownLatch;

public class ThreadSynchronization {

    // 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.
    private 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 to signal on
        new Thread(() -> worker(latch)).start();

        // Block until we receive a signal from the worker thread
        latch.await();
    }
}

To run the program:

$ javac ThreadSynchronization.java
$ java ThreadSynchronization
working...done

In this Java version, we use a CountDownLatch to synchronize between threads. The CountDownLatch is initialized with a count of 1, and the main thread waits on it using await(). The worker thread counts down the latch when it’s finished, which unblocks the main thread.

If you removed the latch.await() line from this program, the main thread would exit before the worker thread even started its work.

This example demonstrates a simple way to coordinate between threads in Java. For more complex scenarios involving multiple threads, you might prefer to use other concurrency utilities provided by Java, such as ExecutorService or CompletableFuture.