All pastes #885958 Raw Edit

Miscellany

public text v1 · immutable
#885958 ·published 2008-01-31 08:28 UTC
rendered paste body


public class Alternate {
	private Object monitor = new Object();
	private Object doneMonitor = new Object();
	public static String[] halls = ResidentInput.getHallNames();
	public static int[] rooms = ResidentInput.getHallRooms();
	public String[] enrollRequests;
	public String name;
	
	public class Alternator implements Runnable {
		public String name;
		public Alternator(String name) {
			this.name = name;
			if (name.equalsIgnoreCase("Tom"))
				enrollRequests = ResidentInput.getEnrollRequestsTom();
			if (name.equalsIgnoreCase("Jerry"))
				enrollRequests = ResidentInput.getEnrollRequestsJerry();
		}
		
		public void run() {
				synchronized(monitor) {			
					for(int x = 0;x < enrollRequests.length;x++){
		    			boolean found = false;
		    			String currentReq = enrollRequests[x];
		    			for(int y = 0;y < halls.length && found == false;y++){
		    				if (currentReq.equalsIgnoreCase(halls[y])){
		    					found = true;
		    					if (rooms[y]>0){
		    						rooms[y]--;
		    						System.out.println(name + " - " + currentReq + " - OK");
		    					}
		    					else
		    						System.out.println(name + " - " + currentReq + " - REJECTED");
		    				}
		    			}
		    			if (found == false)
		    			{
		    				System.out.println(name + " - " + currentReq + " - NONEXIST");
		    			}
					monitor.notifyAll();
					try {
						monitor.wait();
					} catch (InterruptedException ie) {
						ie.printStackTrace();
					}
				}
			}
			synchronized(doneMonitor) {
				doneMonitor.notifyAll();
			}
		}
	}
	
	public void go(String[] args) {
		Thread t1 = new Thread(new Alternator("Tom"));
		Thread t2 = new Thread(new Alternator("Jerry"));
		synchronized(monitor) {
			t1.start();
			try {
				monitor.wait();
			} catch (InterruptedException ie) {
				ie.printStackTrace();
			}
			t2.start();
		}
		synchronized(doneMonitor) {
			try {
				doneMonitor.wait();
			} catch (InterruptedException ie) {
				ie.printStackTrace();
			}
		}
	}

	/**
	 * @param args
	 */
	public static void main (String[] args) {
		Alternate a = new Alternate();
		a.go(args);
	}

}