
Untitled
By: a guest on
May 1st, 2012 | syntax:
Java | size: 2.10 KB | hits: 60 | expires: Never
/**
* Self test for Communicator.
* Derrick McMillen, Spring 2012
* Please don't submit your solution with my testcase in it. kkthxbai.
*
* Watchout for a case where you join a blocked thread last - it will
* block the terminal which is no fun.
*
* For example, 3 speakers and 2 listeners where the last thread joined
* is a speaker. The blocked speaker is the last thread. Not very dirigent!
*/
public static void selfTest() {
KThread socrates = new KThread(new Philosopher("Socrates", 12));
KThread pythagoras = new KThread(new Philosopher("Pythagoas", 5));
KThread heraclitus = new KThread(new Philosopher("Heraclitus", 7));
Philosopher ar = new Philosopher("Aristotle");
Philosopher pl = new Philosopher("Plato");
Philosopher th = new Philosopher("Thales");
KThread plato = new KThread(pl);
KThread aristotle = new KThread(ar);
KThread thales = new KThread(th);
socrates.fork();
pythagoras.fork();
heraclitus.fork();
plato.fork();
aristotle.fork();
thales.fork();
socrates.join();
pythagoras.join();
heraclitus.join();
plato.join();
aristotle.join();
thales.join();
}
private static class Philosopher implements Runnable {
public static Communicator comm = new Communicator();
public String name;
public Integer msg;
public String heard = "";
public Philosopher(String name) {
this.name = name;
}
public Philosopher(String name, Integer msg) {
this(name);
this.msg = msg;
}
public void run() {
if(msg != null) {
comm.speak(msg.intValue());
System.out.printf("%s says %d \n", name, msg.intValue());
} else {
int h = comm.listen();
heard += h + ", ";
System.out.printf("%s heard %d \n", name, h);
}
}
}