/* * this method always checks the status of the bridge and updates the status * of the bridge before letting the bus in , and also gives the waiting * numbers to the subsequent trucks if there are already 4 trucks on the * bridge */ public void checkTheBridge(Truck aTruck) { if (aTruck.getDirection().equals("left") && aTruck.getWaitingNumber() == 0) aTruck.setWaitingNumber(updateWaitingTruck(1, 1)); else { if (aTruck.getWaitingNumber() == 0) aTruck.setWaitingNumber(updateWaitingTruck(2, 1)); } System.out.println( "For waiting number " + aTruck.getWaitingNumber() + "new truck on the bridge"); synchronized (bridgeLock) { try { while (aTruck.getWeight() + BridgeWeight > maxBridgeWeight || bridgeLeftCount + bridgeRightCount >= 4 || aTruck.getWaitingNumber() != servingTokenNumber) { bridgeLock.notifyAll(); bridgeLock.wait(); } BridgeWeight = BridgeWeight + aTruck.getWeight(); if (aTruck.getDirection().equals("left")) bridgeLeftCount++; else bridgeRightCount++; System.out.println( "Number of Trucks on Bridge " + (bridgeLeftCount + bridgeRightCount) + " Weight of the bridge " + BridgeWeight); servingTokenNumber++; bridgeLock.notifyAll(); } catch (Exception e) { System.out.println("Error:" + e); } } }
// this method enables the truck to cross the bridge public void crossthisTruck(Truck aTruck) { checkTheBridge(aTruck); // truck is on the road out side synchronized Block try { Thread.sleep(new Random().nextInt(200)); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (bridgeLock) { if (aTruck.getDirection().equals("left")) bridgeLeftCount--; else bridgeRightCount--; BridgeWeight -= aTruck.getWeight(); } System.out.println(aTruck.getWaitingNumber() + "leaving Bridge"); }