We help IT Professionals succeed at work.
Get Started
Troubleshooting Question

Thread Synchronization with equal sharing

Simon Leung
Simon Leung asked
on
85 Views
Last Modified: 2020-11-25
In the code below, four threads are supposed to take turns to buy the ticket. However, it seems that only 2 threads buys more tickets than other.

Any idea how to communicate among the threads such that each one take turn to buy ?

Thx

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();
   }
}

Comment
Watch Question
CERTIFIED EXPERT
Commented:
This problem has been solved!
Unlock 1 Answer and 24 Comments.
See Answer
Why Experts Exchange?

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.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant

An Experts Exchange subscription includes unlimited access to online courses.

Get Started
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE