import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; class Counter { private int value = 0; private final ReadWriteLock lock = new ReentrantReadWriteLock(); public void increment() { lock.writeLock().lock(); // Acquire write lock try { value++; System.out.println(Thread.currentThread().getName() + " increments value to: " + value); } finally { lock.writeLock().unlock(); // Release write lock } } public int getValue() { lock.readLock().lock(); // Acquire read lock try { return value; } finally { lock.readLock().unlock(); // Release read lock } } } public class Main { public static void main(String[] args) { final Counter counter = new Counter(); Runnable reader = () -> { for (int i = 0; i < 5; i++) { int value = counter.getValue(); System.out.println(Thread.currentThread().getName() + " reads value: " + value); try { Thread.sleep(1000); // Simulate delay } catch (InterruptedException e) { e.printStackTrace(); } } }; Runnable writer = () -> { for (int i = 0; i < 5; i++) { counter.increment(); try { Thread.sleep(1000); // Simulate delay } catch (InterruptedException e) { e.printStackTrace(); } } }; // Create and start multiple reader threads Thread[] readers = new Thread[3]; for (int i = 0; i < 3; i++) { readers[i] = new Thread(reader, "Reader-" + (i + 1)); readers[i].start(); } // Create and start a single writer thread Thread writerThread = new Thread(writer, "Writer"); writerThread.start(); // Wait for all threads to finish try { writerThread.join(); for (Thread readerThread : readers) { readerThread.join(); } } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Final value: " + counter.getValue()); } }