import java.util.ArrayList; class HeatingTable1{ // A monitor int numOnTable = 0; int numProduced = 0; // Invariants holds initially int numServed =0; final int TABLE_SIZE; final int NUM_TO_BE_MADE; // INVARIANTS: // 1) 0 <= numOnTable <= TABLE_SIZE // 2) numProduced <= NUM_TO_BE_MADE HeatingTable1(int maxOn, int max) { TABLE_SIZE = maxOn; NUM_TO_BE_MADE = max; } // Invariants holds initially as long as // parameters are none-negative synchronized boolean putPlate(Kokk c) { if (numOnTable == TABLE_SIZE) { return false; } numProduced++; // 0 <= numOnTable < TABLE_SIZE numOnTable++; // 0 < numOnTable <= TABLE_SIZE System.out.println("Kokk no:"+c.ind+", laget tallerken no:"+numProduced); return true; } synchronized boolean getPlate(Kelner w) { if (numOnTable == 0) return false; // 0 < numOnTable <= TABLE_SIZE numServed++; numOnTable--; // 0 <= numOnTable < TABLE_SIZE System.out.println("Kelner no:"+w.ind+", serverte tallerken no:"+numServed); return true; } } // end class HeatingTable1 public class Restaurant1{ HeatingTable1 table; Restaurant1(String[] args) { table = new HeatingTable1(3,Integer.parseInt(args[0])); int numKokks = Integer.parseInt(args[1]), c = numKokks; int numKelners = Integer.parseInt(args[2]), w = numKelners; Thread [] t = new Thread[numKokks+numKelners]; while (numKelners-- > 0) ( t[numKelners+1] = new Kelner(table,numKelners+1 )).start(); while (numKokks-- > 0) ( t[numKokks + w] = new Kokk(table,numKokks+1)).start(); for(Thread tt : t) try{tt.join();} catch (Exception e){}; // The main-thread is now 'alone‘. Do other stuff .. } public static void main(String[] args) { Restaurant1 rest; if (args.length != 3) { System.out.println("use: >java Restaurant1 <#Kokks> <#Kelners>"); }else{ rest = new Restaurant1(args); } } // end main } // end Restaurant class Kokk extends Thread { HeatingTable1 tab; int ind; int dishNum; Kokk(HeatingTable1 shared, int ind) { tab = shared; this.ind = ind; } public void run() { try { while (tab.numProduced < tab.NUM_TO_BE_MADE) { if (tab.putPlate(this) ) { // lag neste tallerken } sleep((long) (1000 * Math.random())); } } catch (InterruptedException e) {} System.out.println("Kokk "+ind+" ferdig: " ); } } // end Kokk class Kelner extends Thread { HeatingTable1 tab; int ind; Kelner(HeatingTable1 shared, int ind) { tab = shared; this.ind = ind; } public void run() { try { while ( tab.numServed < tab.NUM_TO_BE_MADE) { if ( tab.getPlate(this)) { // server tallerken } sleep((long) (1000 * Math.random())); } } catch (InterruptedException e) {} System.out.println("Kelner " + ind+" ferdig"); } } // end Kelner