import java.io.*;
import java.util.*;

public class PreThreadModel implements ThreadModel,Runnable {
   private Thread[] pool = null;
   private Runnable task = null;
   private int poolSize = 10;

   public PreThreadModel() {
      try {
         Properties props = new Properties();
         props.load(new FileInputStream("objsvr.properties"));
         poolSize = Integer.parseInt(props.getProperty("pre.thread.size"));
      }
      catch(Exception e) {
         e.printStackTrace(System.err);
      }

      pool = new Thread[poolSize];

      for(int i = 0; i < poolSize; i++) {
         pool[i] = new Thread(this);
         pool[i].start();
      }

      task = null;
   }

   public String getName() {
      return "ThreadPool";
   }

   public void run() {
      Runnable the_task = null;
      while(true) {
System.out.println("PreThreadModel.run()");
         synchronized(this) {
            while(task == null) {
System.out.println("PreThreadModel.run(): wait");
               try {
                  wait();
               }
               catch(Exception ex) {
                  ex.printStackTrace(System.err); 
               }
            }
            the_task = task;
            task = null;
            notify();
         }
         if(the_task != null) {
System.out.println("run task");
            the_task.run();
            the_task = null;
         }
      }
   }

   public void runTask(Runnable task) {
      synchronized(this) {
         while(this.task != null) {
System.out.println("runTask: wait");
            try {
               wait();
            }
            catch(Exception ex) {
               ex.printStackTrace(System.err);
            }
         }
         this.task = task;
         notify();
      }
   }
}
