import java.util.concurrent.atomic.AtomicInteger; /** * The TwoCounters class implements a simple ticket-based locking mechanism for thread synchronization. * It ensures mutual exclusion by generating ticket numbers for threads and allowing access in the order * of ticket issuance. * This class implements the SimpleLock interface. * * The lock() method assigns a ticket number to the calling thread and causes it to wait until its ticket * is being served. * * The unlock() method increments the serving number, allowing the next thread holding the next ticket * to acquire the lock. * * The init(int th) and finish() methods serve as placeholders and do not provide any specific implementation. * * The name() method returns the fully qualified name of the class. */ public class TwoCounters implements SimpleLock { final AtomicInteger ticketNo = new AtomicInteger(0); final AtomicInteger serving = new AtomicInteger(0); @Override public void lock() { final int myTicket = ticketNo.getAndIncrement(); while(true) { final int servingNo = serving.get(); if(myTicket == servingNo) { break; } else { Thread.yield(); } } } @Override public void unlock() { serving.getAndIncrement(); } @Override public void init(int th) { } @Override public void finish() { } public String name() { return getClass().getName(); } }