Java Reference
In-Depth Information
public TaskResult(int taskId, int result) {
this.taskId = taskId;
this.result = result;
}
public int getTaskId() {
return taskId;
}
public int getResult() {
return result;
}
public String toString() {
return "Task Name: Task #" + taskId + ", Task Result:" + result + " seconds";
}
}
Listing 6-56. A Class Whose Object Represents a Callable Task. It Produces a TaskResult as Its Result.
// SleepingTask.java
package com.jdojo.threads;
import java.util.Random;
import java.util.concurrent.Callable;
public class SleepingTask implements Callable<TaskResult> {
private int taskId;
private int loopCounter;
private Random random = new Random();
public SleepingTask(int taskId, int loopCounter) {
this.taskId = taskId;
this.loopCounter = loopCounter;
}
public TaskResult call() throws InterruptedException {
int totalSleepTime = 0 ;
for (int i = 1; i <= loopCounter; i++) {
try {
int sleepTime = random.nextInt(10) + 1;
System.out.println("Task #" + this.taskId + " - Iteration #" + i
+ " is going to sleep for " + sleepTime + " seconds.");
Thread.sleep(sleepTime * 1000);
totalSleepTime = totalSleepTime + sleepTime;
}
catch(InterruptedException e) {
System.out.println("Task #" + this.taskId +
" has been interupted.");
Search WWH ::




Custom Search