Advertisement
Guest User

Untitled

a guest
Feb 17th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.21 KB | None | 0 0
  1. import java.util.concurrent.Semaphore;
  2.  
  3. public class vehicle implements Runnable
  4. {
  5.     static int numCars=0;
  6.    
  7.     private int carNum;
  8.     private boolean north;
  9.     private boolean crossed= false;
  10.     static Semaphore mutex;
  11.  
  12. public vehicle(boolean isNorth)
  13. {
  14.     north=isNorth;
  15.     numCars=numCars+1;
  16.     carNum=numCars;                                                                                                                                                                                                            
  17.    
  18.  
  19.     mutex=new Semaphore(1);
  20.  
  21. }
  22.  
  23. public void run()
  24. {
  25.     System.out.println("car number: "+carNum+" has arrived at bridge.");
  26.     crossBridge();                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  )
  27. }
  28.  
  29. public void setCrossed()
  30. {
  31.     crossed=true;
  32. }
  33.  
  34.  
  35. public int getNumber()
  36. {
  37.     return carNum;
  38. }
  39.  
  40.  
  41.  
  42.  
  43. public Boolean crossBridge()
  44. {
  45.    
  46.     try
  47.     {
  48.         mutex.acquire();
  49.     }
  50.     catch(InterruptedException e)
  51.     {System.out.println("mutex failed to acquire.");}
  52.  
  53.     setCrossed();
  54.     mutex.release();
  55.     System.out.println("car number "+carNum+" has crossed the bridge.");
  56.     return true;
  57. }
  58.  
  59.  
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement