class Buyer3 extends Thread { TicketPool pool;// declare total ticket and initialized it to 100 boolean neverBrought= true; Buyer3(TicketPool pool) { this.pool = pool; } public void run() //override run() here { //loop if availableTicket >0 while(true){ synchronized(pool) { if (neverBrought == false) { try { //wait for execution pool.wait(); }catch(InterruptedException e){ e.printStackTrace(); } } if (pool.getTicket()>0) { // place order: print out "Thread xx reserved ticket --- #n" System.out.println(Thread.currentThread().getName()+" reserved ticket # "+ pool.getTicket()); //delay 10ms: sleep(10) try{ Thread.currentThread().sleep(10); } catch (InterruptedException itro){ System.out.println("sleep is interrupted"); } //payment finished: decrease availableTicket by 1 pool.setTicket(pool.getTicket()-1); //print the leftover tickets System.out.println(Thread.currentThread().getName()+" bought ticket # " + (pool.getTicket()+1) + ", ticket left: "+pool.getTicket()); neverBrought=false; //notify execution pool.notify(); }else { System.exit(0); } } }// go back to buy another once (while loop) }// end of override run() } class TicketPool { int availableTicket; TicketPool(int totalTicket) { this.availableTicket = totalTicket; } void setTicket(int newNumber) { availableTicket = newNumber; } int getTicket(){ return availableTicket; } } public class TicketDemo3{ public static void main (String[] args){ // start 4 threads from a object of class Ticket that implements the "Runnable" interface TicketPool tickets = new TicketPool(10); // start 4 threads from the same object Buyer3 t1 = new Buyer3(tickets); Buyer3 t2 = new Buyer3(tickets); Buyer3 t3 = new Buyer3(tickets); Buyer3 t4 = new Buyer3(tickets); t1.setName("John"); t2.setName("Mike"); t3.setName("Lily"); t4.setName("Mary"); t1.start(); t2.start(); t3.start(); t4.start(); } }
Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.
When asked, what has been your best career decision?
Deciding to stick with EE.
Being involved with EE helped me to grow personally and professionally.
Connect with Certified Experts to gain insight and support on specific technology challenges including:
We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE