Advertisement
heavenriver

Runner.java (synchronized start version)

Apr 14th, 2013
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.12 KB | None | 0 0
  1. package runners_advanced;
  2.  
  3. public class Runner implements Runnable
  4.  
  5.     {
  6.     private int runnerID;
  7.     private Start start;
  8.     public static final int COUNTER = 100;
  9.    
  10.     public Runner(int id, Start s)
  11.         {
  12.         runnerID = id;
  13.         start = s;
  14.         }
  15.    
  16.     public int getRunnerID()
  17.         {
  18.         return runnerID;
  19.         }
  20.    
  21.     public String toString()
  22.         {
  23.         return "Runner " + runnerID;
  24.         }
  25.    
  26.     public void run()
  27.         {
  28.         int metresRun = 0;
  29.         while(metresRun < COUNTER)
  30.             {
  31.             boolean check = start.ready(); // Checks if the current runner is the last runner
  32.             start.setReady(this);
  33.             try
  34.                 {
  35.                 if(start.ready())
  36.                     {
  37.                     if(start.ready() != check)
  38.                         Thread.sleep((long)(Math.random() * 10)); // Makes the last runner sleep so that they don't start before the others all the time
  39.                     metresRun++;
  40.                     Thread.sleep((long)(Math.random() * 10));
  41.                     System.out.println(toString() + " has run " + metresRun + " metres");
  42.                     }
  43.                 else System.out.println(toString() + " waiting...");
  44.                 }
  45.             catch(InterruptedException e)
  46.                 {
  47.                 e.printStackTrace();
  48.                 }
  49.             }
  50.         System.out.println(toString() + " has arrived!");
  51.         }
  52.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement