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

Synchronized in Java

Simon Leung
Simon Leung asked
on
85 Views
Last Modified: 2020-11-02
For the code below, why a single thread will use up all the ticketcounter ? I suppose the lock on ticketpool will be released at the end of the while loop. hence, other thread wait for it should able to get it at once. However, it come out that a single thread will buy all the ticket. Any idea ?

Thx

class Buyer3 extends Thread {
   TicketPool pool;// declare total ticket and initialized it to 100 
    
   
   Buyer3(TicketPool pool)
   {
      this.pool = pool;
   }
   
   public void run() //override run() here 
   {      
      //loop if availableTicket >0    
      
      while(pool.getTicket()>0){
         
         synchronized(pool) {         
                     
           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());
             }
               
      }
         
      }// 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 Task2{
   
   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 7 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