top of page
Interesting Recent Posts :
Writer's pictureRohit chopra

Java : Synchronization Between Threads - Interview Code Example



Introduction: In Java, synchronization can be used to ensure that only one thread can access a critical section of code at a time. This is useful when multiple threads need to access and modify a shared resource concurrently, and we want to avoid race conditions and incorrect results.


There are several other concurrency constructs like Semphore and Atomic Integers which you can checkout with examples.


Here is an example code that demonstrates the use of synchronization to print odd and even numbers alternatively using two threads:


public class OddEvenPrinter {
    private int count = 1;
    private int limit;
    private boolean isOdd;
    
    public OddEvenPrinter(int limit, boolean isOdd) {
        this.limit = limit;
        this.isOdd = isOdd;
    }
    
    public synchronized void printNumber() {
        while (count <= limit) {
            if ((count % 2 == 0 && !isOdd) || (count % 2 == 1 && isOdd)) {
                System.out.println(Thread.currentThread().getName() + ": " + count);
                count++;
                notify();
            } else {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

In this example, we create a class OddEvenPrinter that has a count variable that represents the number to be printed, a limit variable that represents the maximum number to be printed, and a isOdd variable that determines whether to print odd or even numbers.

The printNumber() method is synchronized, which means that only one thread can execute it at a time. The method uses a while loop to continue printing numbers until the count variable reaches the limit variable.

If the count variable is even and isOdd is false, or the count variable is odd and isOdd is true, then the method prints the number, increments the count variable, and notifies other threads that may be waiting to access the method.

If the condition is not met, then the method waits by calling wait() until another thread calls notify().

Here is an example code that demonstrates how to use the OddEvenPrinter class to print odd and even numbers alternatively using two threads:


public class OddEvenPrinterDemo {
    public static void main(String[] args) {
        OddEvenPrinter oddPrinter = new OddEvenPrinter(10, true);
        OddEvenPrinter evenPrinter = new OddEvenPrinter(10, false);
        
        Runnable oddTask = () -> oddPrinter.printNumber();
        Runnable evenTask = () -> evenPrinter.printNumber();
        
        Thread oddThread = new Thread(oddTask, "Odd Thread");
        Thread evenThread = new Thread(evenTask, "Even Thread");
        
        oddThread.start();
        evenThread.start();
    }
}

In this example, we create two OddEvenPrinter objects, one for odd numbers and one for even numbers. We then create two Runnable tasks, one for printing odd numbers and one for printing even numbers.

We create two threads that execute the tasks, and start the threads. The OddEvenPrinter objects ensure that the threads print odd and even numbers alternatively using synchronization.

Sample Output:


Odd Thread: 1Even Thread: 2Odd Thread: 3Even Thread: 4Odd Thread: 5Even Thread: 6Odd Thread: 7Even Thread: 8Odd Thread: 9Even Thread: 10

As expected, the threads print odd and even numbers alternatively until the limit of 10 is reached. This demonstrates how synchronization can be used to ensure that multiple threads access a shared resource concurrently in a controlled and coordinated

6 views

Recent Posts

See All

Comments


bottom of page