Advertisement
Guest User

Untitled

a guest
Jul 16th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.21 KB | None | 0 0
  1. import java.util.concurrent.atomic.*;
  2.  
  3. public class ParkingLot{
  4.     private int capacity;
  5.     AtomicInteger cars;
  6.    
  7.     boolean isFull(){
  8.         if(cars.get() == capacity){
  9.             return true;
  10.         }
  11.         return false;
  12.     }
  13.    
  14.     boolean isEmpty(){
  15.         if(cars.get() == 0){
  16.             return true;
  17.         }
  18.         return false;
  19.     }
  20.    
  21.     ParkingLot(int capacity){
  22.         this.capacity=capacity;
  23.         cars= new AtomicInteger(0);
  24.        
  25.         //Producer
  26.         new Thread(){
  27.             public void run(){
  28.                 synchronized(cars){
  29.                     while(true){
  30.                         while(isFull()){
  31.                             try{
  32.                                 cars.wait();
  33.                             }
  34.                             catch(InterruptedException ex){}
  35.                         }
  36.                         System.out.println("TOTAL CARS:"+cars.get()+"/"+capacity+"  |   Adding new car");
  37.                         cars.getAndIncrement();
  38.                         try{
  39.                             sleep(1000);
  40.                             cars.notify();
  41.                         }
  42.                         catch(InterruptedException ex){}
  43.                     }
  44.                 }
  45.             }
  46.         }.start();
  47.        
  48.         //Consumer
  49.         new Thread(){
  50.             public void run(){
  51.                 synchronized(cars){
  52.                     while(true){
  53.                         while(isEmpty()){
  54.                             try{
  55.                                 cars.wait();
  56.                             }
  57.                             catch(InterruptedException ex){}
  58.                         }
  59.                         System.out.println("TOTAL CARS:"+cars.get()+"/"+capacity+"  | Removing a car");
  60.                         cars.getAndDecrement();
  61.                         try{
  62.                             sleep(1000);
  63.                             cars.notify();
  64.                         }
  65.                         catch(InterruptedException ex){}
  66.                     }
  67.                 }
  68.             }
  69.         }.start();
  70.     }
  71.    
  72.     public static void main(String args[]){
  73.         ParkingLot p= new ParkingLot(10);
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement