Tuesday 5 May 2009

2-A SIMPLE PROCESS SIMULATION

II. I added a similar task with monitoring capabilities. MonitorTask has the same mechanisms as the previous JobTask but also it calculates for all the tasks in the runners queue the total of their remaining tasks as in:

sumRunningTasks += runningTasks[i].taskWeight - runningTasks[i].taskWeightCounter;
The code is below:
package stochasticprocess;

public class JobQueue2 {

private final static int NUMRUNNERS = 5;

public JobQueue2() {
}
public static void main(String[] args) {
JobTask2[] runners = new JobTask2[NUMRUNNERS];

for (int i = 0; i < NUMRUNNERS; i++) {
runners[i] = new JobTask2(i);
runners[i].setPriority(2);
}

for (int i = 0; i < NUMRUNNERS; i++)
runners[i].start();

MonitorTask monitorTask = new MonitorTask(999, runners);
monitorTask.setPriority(1);
monitorTask.start();
}
}

class JobTask2 extends Thread {
public int taskWeight = 400;
public int taskWeightCounter = 1;
private int taskId;

public JobTask2(int taskId) {
this.taskId = taskId;
}

public void run() {
while (taskWeightCounter < taskWeight) {
taskWeightCounter++;

try {
sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

if ((taskWeightCounter % 50) == 0)
System.out.println("Job Task Thread #" + taskId + ", taskWeightCounter = " + taskWeightCounter);
}
}
}
class MonitorTask extends Thread {
private int taskWeight = 400;
public int taskWeightCounter = 1;
private int taskId;
JobTask2[] runningTasks;
int sumRunningTasks;

public MonitorTask(int taskId, JobTask2[] runnerTasks) {
this.taskId = taskId;
this.runningTasks = runnerTasks;
}

public void run() {
while (taskWeightCounter < taskWeight) {
taskWeightCounter++;
try {
sleep(20);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

if ((taskWeightCounter % 50) == 0)
{
sumRunningTasks = 0;
for(int i=0; i < runningTasks.length; i++)
sumRunningTasks += runningTasks[i].taskWeight - runningTasks[i].taskWeightCounter;
System.out.print("==========================================>");
System.out.println("Monitor Task Thread # Running Job Tasks=" + sumRunningTasks);
System.out.println("Monitor Task Thread #" + taskId + ", taskWeightCounter = " + taskWeightCounter);
}
}
}
}