/**
 * Worker.java
 * Implement what worker should do in this class.
 * @author Xuan Ngo
 */
import java.lang.Thread;
import java.util.Random;
import java.util.ArrayList;

public class Worker extends Thread 
{
  private String m_sWorkerName = "";
  private ArrayList<String> m_aJobsList = null;
  private String m_sJobName = "";
  
  public Worker()
  {}
  
  /**
   * Demonstrate how to pass values from Manager class to Worker class.
   * @param sWorkerName
   * @param aJobsList
   */
  public void set(String sWorkerName, ArrayList<String> aJobsList)
  {
    this.m_sWorkerName = sWorkerName;
    this.m_aJobsList = aJobsList;
    
    this.getJob();
  }
  /**
   * Get the job and remove it from the job list so that other workers will
   *  not take the same job.
   * Synchronized keyword is used so that other workers can't take the same job.
   */
  private synchronized void getJob()
  {
    if(this.m_aJobsList.size()!=0)
      this.m_sJobName = this.m_aJobsList.remove(0);
  }
  
  /**
   * This method will run when Worker.start() is called.
   * All the logics should be put in here. This is like the main() of a program.
   */
  public void run()
  {
    /**
     * Put a random sleep time to simulate work time.
     */
    Random oRandom = new Random();
    int iSleepTime = oRandom.nextInt(5000);
    System.out.println("\t"+this.m_sWorkerName+": Working on Job"+this.m_sJobName+" for " +iSleepTime +"ms.");
    try
    {
      Thread.sleep(iSleepTime);
    }
    catch(Exception ex)
    {
      System.out.println(ex);
    }
    System.out.println("\t"+this.m_sWorkerName+": Done Job"+this.m_sJobName+".");
  }
  
}

