georgeB96

TunnelTest class

Dec 3rd, 2021
770
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. public class TunnelTest {
  3.     public static void main(String[] args) {
  4.         Tunnel portTunnel = new Tunnel(10);
  5.        
  6.         for(int j = 1;j<= 15; j++) {
  7.             new Thread(new Car(portTunnel, j)).start();
  8.             try {
  9.                 Thread.sleep(200);
  10.             } catch(InterruptedException e) {
  11.                
  12.             }
  13.         }
  14.     }
  15.    
  16.    
  17. }
  18.  
  19. class Car implements Runnable {
  20.    
  21.     //properties
  22.     private Tunnel t;
  23.     private int num;
  24.    
  25.     //constructor
  26.     public Car(Tunnel t1, int n) {
  27.         t = t1;
  28.         num = n;
  29.     }
  30.    
  31.     public void run() {
  32.         t.waitTunnel(num);
  33.        
  34.         try {
  35.             Thread.sleep(10000);
  36.         } catch (InterruptedException e) {
  37.             System.out.println("Car "+ num + " is crossing the tunnel");
  38.         }
  39.        
  40.        
  41.         t.signalTunnel(num);
  42.     }
  43. }
  44.  
  45. class Tunnel {
  46.    
  47.     //properties
  48.     private int count;
  49.    
  50.     //constructor
  51.     public Tunnel(int c) {
  52.         count = c;
  53.     }
  54.    
  55.     //critical resource
  56.     public synchronized void waitTunnel(int n){
  57.         // if count is zero the process must wait
  58.         while(count == 0)
  59.             try{
  60.                 wait();
  61.             } catch(InterruptedException e){}
  62.  
  63.          // otherwise the process can continue
  64.          count--;
  65.          System.out.println("Car " +n+ " has Entered. " +  count + " spaces left in tunnel.");
  66.  
  67.     }
  68.    
  69.     public synchronized void signalTunnel(int n) {
  70.          count++;
  71.          System.out.println("Car "+n+" has left. " +  count + " spaces left in tunnel.");
  72.          notify();
  73.  
  74.     }
  75. }
  76.  
  77.  
RAW Paste Data