Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class Ticket {
private String name;
private String status;
public Ticket(String name, String status) {
this.name = name;
this.status = status;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
class TicketingSystem {
static final Ticket number1 = new Ticket("Number1", "open");
static final Ticket number2 = new Ticket("Number2", "open");
static Ticket[] numberList = new Ticket[] {number1, number2};
public static String getNextAvailableTicket() {
String availableNumber = null;
try {
for (Ticket number: numberList) {
if(number.getStatus() == "open") {
number.setStatus("pending"); // changing the state of the object
System.out.printf("Thread name %s - number found %s \n",Thread.currentThread().getName(), number.getName());
Thread.sleep(5000); // assume processing some business logic
number.setStatus("open"); // decide to put it back due to some error
availableNumber = number.getName();
break;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return availableNumber;
}
}
class TicketCounter extends Thread {
TicketingSystem ticketingSystem;
public TicketCounter(String name) {
this.setName(name);
start();
}
@Override
public void run() {
System.out.println(TicketingSystem.getNextAvailableTicket());
}
}
public class SyncExample {
public static void main(String[] args) {
try {
TicketingSystem ts = new TicketingSystem();
TicketCounter tc1 = new TicketCounter("Thread 1");
Thread.sleep(1000);
TicketCounter tc2 = new TicketCounter("Thread 2");
tc1.join();
tc2.join();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment