title: Threading in Java (practicing for college)
body: <blockquote>
    <p>Create a program that simulates training at an athletic stadium, 
    there is one track in the stadium that can be used by up to 5 people at a time 
    and the coach does not allow that number to exceed, but when some of the athletes finish their run (2sec) 
    and free up space then notify other athlete for running.</p>
  </blockquote>
  
  <p>After 2 seconds, all processes are frozen</p>
  
  <p>My question is, could anyone explain to me why something like this does not work and how to handle this problem?</p>
  
  <pre><code>class JoggingTrack {
      public int numOfAthlete;
  
      public JoggingTrack() {
          this.numOfAthlete = 0;
      }
  
      @Override
      public String toString() {
          return "\nNumber of Athlete: " + numOfAthlete + "\n";
      }
  }
  
  class Athlete extends Thread {
  
      private JoggingTrack track;
      private boolean running;
  
      public Athlete(JoggingTrack s) {
          this.track = s;
          this.running = false;
      }
  
      public synchronized boolean thereIsSpace() {
          if(track.numOfAthlete &lt; 5) {
              return true;
          }
          return false;
      }
  
      public synchronized void addAthlete() {
          track.numOfAthlete++;
          this.running = true;
      }
  
      public synchronized void removeAthlete() {
          track.numOfAthlete--;
          this.running = false;
      }
  
      @Override
      public void run() {
          try {
              while(true) {
                  while(!this.thereIsSpace()) {
                      wait();
                  }
                  while(!this.running) {
                      addAthlete();
                      sleep(2000);
                  } 
                  while(this.running) {
                      removeAthlete();
                      notify();
                  }
              }
          } catch (Exception e) {
          }
      }
  
  }
  
  public class Program {
      static JoggingTrack track;
      static Athlete[] a;
  
      public static void main(String[] args) {
          track = new JoggingTrack();
          a = new Athlete[10];
          for(int i = 0; i &lt; 10; i++) {
              a[i] = new Athlete(track);
              a[i].start();
          }
          while(true) {
              try {
                  System.out.println(track);
                  Thread.sleep(500);
              } catch (Exception e) {
              }
          }
      }
  }
  </code></pre>