import java.util.HashMap; import java.util.Map; import java.util.Random; public class H20Match { public static final int MAXSROUTINETIME = 1500; public enum Item { CAP, WINGS, PARASOL; public String toString() { return super.toString().toLowerCase(); } }; private Random rndGen = new Random(); private Pool pool = new Pool(); public void go() { new Thread(new MC()).start(); for (Item i : Item.values()) { new Thread(new Ballerina(i)).start(); } } public static void main(String[] args) { new H20Match().go(); } class MC implements Runnable { @Override public void run() { while (true) { switch (Item.values()[rndGen.nextInt(Item.values().length)]) { case CAP: System.out.println("MC adds wings and parasol to the pool"); pool.add(Item.WINGS); pool.add(Item.PARASOL); break; case WINGS: System.out.println("MC adds cap and parasol to the pool"); pool.add(Item.CAP); pool.add(Item.PARASOL); break; case PARASOL: System.out.println("MC adds cap and wings to the pool"); pool.add(Item.CAP); pool.add(Item.WINGS); break; } } } } class Ballerina implements Runnable { private Item owns; public Ballerina(Item owns) { this.owns = owns; } @Override public void run() { while (true) { System.out.println("Ballerina jumps in the pool with " + owns); pool.add(owns); pool.test(); try { Thread.sleep(rndGen.nextInt(MAXSROUTINETIME)); // Routine } catch (InterruptedException e) { } pool.clear(); } } } class Pool { private Map pool = new HashMap(); public Pool() { for (Item i : Item.values()) { pool.put(i, 0); } } public void add(Item item) { pool.put(item, pool.get(item).intValue() + 1); } public void clear() { for (Item i : Item.values()) { pool.put(i, 0); } } public void test() { if (pool.get(Item.CAP) == 0) { System.err .println("Ballerina enters pool without cap, frizzes hair, and leaves in shame."); System.exit(1); } if (pool.get(Item.WINGS) == 0) { System.err .println("Ballerina enters pool without wings and drowns."); System.exit(1); } if (pool.get(Item.PARASOL) == 0) { System.err .println("Ballerina enters pool without parasol. What follows is too horrible to describe."); System.exit(1); } for (Item item : Item.values()) { if (pool.get(item) > 1) { System.err .println("Ballerina drowns. Death blamed on too many " + item + "(s) in the pool"); System.exit(1); } } } } }