View Single Post
  #2 (permalink)  
Old 11-20-2007, 01:11 AM
hardwired hardwired is offline
Senior Member
 
Join Date: Jul 2007
Posts: 1,015
hardwired is on a distinguished road
Code:
import java.util.Random; public class GarageTest { public static void main(String[] args) { Garage garage = new Garage(); Entrance entrance1 = new Entrance(garage, 1); entrance1.start(); Exit exit1 = new Exit(garage, 1); exit1.start(); Entrance entrance2 = new Entrance(garage, 2); entrance2.start(); Exit exit2 = new Exit(garage, 2); exit2.start(); } } class Garage { public static int TOTAL = 10; int currentNumber = 0; public synchronized void enter(int id, int carNumber) { while (currentNumber == TOTAL) { try { wait(); } catch (InterruptedException e) { } } currentNumber++; System.out.printf("Car %2d entered at %d " + "currentNumber = %d%n", carNumber, id, currentNumber); notifyAll(); } public synchronized void exit(int id) { while (currentNumber == 0) { try { wait(); } catch (InterruptedException e) { } } currentNumber--; System.out.println("Car exited at " + id + " currentNumber = " + currentNumber); notifyAll(); } } class Entrance extends Thread { Garage garage; int number; public Entrance(Garage garage, int threadNum) { this.garage = garage; number = threadNum; } public void run() { for(int j = 0; j < 10; j++) { garage.enter(number, j+1); } } } class Exit extends Thread { Garage garage; int number; Random seed = new Random(); public Exit(Garage garage, int threadNum) { this.garage = garage; number = threadNum; } public void run() { for (int j = 0; j < 10; j++) { garage.exit(number); try { sleep(2000 + seed.nextInt(3000)); } catch (InterruptedException e) { break; } } } }
Reply With Quote