/* * TownHall -- An accurate model or social commentary? * * TownHall runs as an application and illustrates multiple threads. */ import java.lang.*; import java.util.*; class SynchronizedQueue extends Vector { private int count; private boolean started; private boolean waiting; private int writers; SynchronizedQueue() { count = 0; started = false; } public synchronized void checkIn () { started = true; count++; } public synchronized void checkOut () { count--; notify(); } public synchronized void enqueue(Object elt) { super.addElement(elt); notify(); } public synchronized boolean anyoneLeft() { if (!started) return true; if (count > 0) return true; else return false; } public synchronized Object dequeue() { Object ret; while (anyoneLeft() && (super.elementCount == 0)) { try { wait(); } catch (InterruptedException x) { } } if (super.elementCount > 0) { ret = super.firstElement(); super.removeElement(ret); } else { ret = null; } return ret; } } class Speaker extends Thread { int id; int speech_count; SynchronizedQueue my_soapbox; static String nouns[] = { "dogs", "cats", "elephants", "donkeys", "houses", "monkeys", "cars", "bicycles", "computers", "music", "books" }; static String ends[] = { "outlawed", "banned", "imported", "discouraged", "sold", "bought", "given away", "made mandatory", "encouraged", "deported", "exported" }; Speaker(int new_id, int turns, SynchronizedQueue forum) { id = new_id; speech_count = turns; my_soapbox = forum; } public void run() { int i; Random r = new Random(); my_soapbox.checkIn(); my_soapbox.enqueue("speaker "+ id +" stepping onto soapbox"); for (i = 0; i < speech_count; i++) { try { sleep((r.nextInt() % 10) * 10); } catch (Exception e) { } my_soapbox.enqueue("speaker "+ id +": " + nouns[Math.abs(r.nextInt())%nouns.length] + " should be " + ends[Math.abs(r.nextInt())%ends.length]); } my_soapbox.enqueue("speaker "+ id +" stepping off soapbox"); my_soapbox.checkOut(); } } class MC extends Thread { SynchronizedQueue podium; MC(SynchronizedQueue new_forum) { podium = new_forum; } public void run() { Object utterance; System.out.println("MC here: good morning."); utterance = podium.dequeue(); while (utterance != null) { System.out.println(utterance); utterance = podium.dequeue(); } System.out.println("MC here: good night."); } } class TownHall { static SynchronizedQueue podium; static int num_speakers; public static void main(String args[]) { num_speakers = 5; podium = new SynchronizedQueue(); Speaker[] contenders = new Speaker[num_speakers]; MC georgeWill = new MC(podium); georgeWill.start(); for(int i = 0; i < num_speakers; i++) { contenders[i] = new Speaker(i, 10, podium); contenders[i].start(); } try { georgeWill.join(); } catch (InterruptedException x) { } System.out.println("Town Hall closing."); } }