Advertisement
Guest User

Untitled

a guest
Jul 16th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.58 KB | None | 0 0
  1. import java.util.concurrent.*;
  2. import java.util.concurrent.atomic.*;
  3.  
  4. public class Elevator{
  5.     private int floor;
  6.     int current_floor=0;
  7.     AtomicBoolean busy= new AtomicBoolean(false);
  8.    
  9.     Elevator(int num_floor){
  10.         floor= 0;
  11.     }
  12.        
  13.     public void call(int floor){
  14.         new Thread(){
  15.             public void run(){
  16.                 synchronized(busy){
  17.                     while(busy.get()){
  18.                         try{
  19.                             System.out.println("Call in wait");
  20.                             busy.wait();
  21.                         }
  22.                         catch(InterruptedException ex){}
  23.                         move(floor);
  24.                     }
  25.                     move(floor);
  26.                 }
  27.             }
  28.         }.start();
  29.     }
  30.    
  31.     public void move(int floor){
  32.         synchronized(busy){
  33.             while(busy.get()){
  34.                 try{
  35.                     busy.wait();
  36.                 }
  37.                 catch(InterruptedException ex){}
  38.             }
  39.             try{
  40.                 busy.set(true);
  41.                 System.out.println("Leaving floor "+ current_floor);
  42.                 Thread.currentThread().sleep(2000);
  43.                 current_floor=floor;
  44.                 System.out.println("Reaching floor "+ current_floor);
  45.                 busy.set(false);
  46.                 busy.notify();
  47.             }
  48.             catch(InterruptedException ex){}
  49.         }
  50.     }
  51.    
  52.     public static void main(String args[]){
  53.         Elevator e= new Elevator(10);
  54.         e.call(1);
  55.         e.call(2);
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement