Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 1st, 2012  |  syntax: Java  |  size: 2.10 KB  |  hits: 60  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1.  
  2.  
  3. /**
  4.      * Self test for Communicator.
  5.      * Derrick McMillen, Spring 2012
  6.      * Please don't submit your solution with my testcase in it. kkthxbai.
  7.      *
  8.      * Watchout for a case where you join a blocked thread last - it will
  9.      * block the terminal which is no fun.
  10.      *
  11.      * For example, 3 speakers and 2 listeners where the last thread joined
  12.      * is a speaker. The blocked speaker is the last thread. Not very dirigent!
  13.      */
  14.     public static void selfTest() {
  15.         KThread socrates = new KThread(new Philosopher("Socrates", 12));
  16.         KThread pythagoras = new KThread(new Philosopher("Pythagoas", 5));
  17.         KThread heraclitus = new KThread(new Philosopher("Heraclitus", 7));
  18.  
  19.         Philosopher ar = new Philosopher("Aristotle");
  20.         Philosopher pl = new Philosopher("Plato");
  21.         Philosopher th = new Philosopher("Thales");
  22.  
  23.         KThread plato = new KThread(pl);
  24.         KThread aristotle = new KThread(ar);
  25.         KThread thales = new KThread(th);
  26.  
  27.         socrates.fork();
  28.         pythagoras.fork();
  29.         heraclitus.fork();
  30.  
  31.         plato.fork();
  32.         aristotle.fork();
  33.         thales.fork();
  34.  
  35.         socrates.join();
  36.         pythagoras.join();
  37.         heraclitus.join();
  38.  
  39.         plato.join();
  40.         aristotle.join();
  41.         thales.join();
  42.     }
  43.  
  44. private static class Philosopher implements Runnable {
  45.         public static Communicator comm = new Communicator();
  46.         public String name;
  47.         public Integer msg;
  48.         public String heard = "";
  49.  
  50.         public Philosopher(String name) {
  51.             this.name = name;
  52.         }
  53.  
  54.         public Philosopher(String name, Integer msg) {
  55.             this(name);
  56.             this.msg = msg;
  57.         }
  58.  
  59.         public void run() {
  60.             if(msg != null) {
  61.                 comm.speak(msg.intValue());
  62.                 System.out.printf("%s says %d \n", name, msg.intValue());
  63.             } else {
  64.                 int h = comm.listen();
  65.                 heard += h + ", ";
  66.                 System.out.printf("%s heard %d \n", name,  h);
  67.             }
  68.         }
  69.     }