Page 104 - DCAP103_Principle of operating system
P. 104
Unit 3: Process Management-II
long endTime = System.currentTimeMillis( ); Notes
d.setTime(endTime);
System.out.println(“Ending task” + id + “ at ” + df.format(d) +
“after ” + (endTime - startTime) + “milliseconds”);
}
}
We have made this class a Runnable object so that we can run multiple instances of it in multiple
threads.
public class ThreadTest {
public static void main(String[] args) {
int nThreads = Integer.parseInt(args[0]);
long n = Long.parseLong(args[1]);
Thread t[] = new Thread[nThreads];
for (int i = 0; i < t.length; i++) {
t[i] = new Thread(new Task(n, “Task” + i));
t[i].start( );
}
for (int i = 0; i < t.length; i++) {
try {
t[i].join( );
} catch (InterruptedException ie) {}
}
}
}
Running this code with three threads produces this kind of output:
Starting task: Task 2 at 00:04:30:324
Starting task: Task 0 at 00:04:30:334
Starting task: Task 1 at 00:04:30:345
Ending task: Task 1 at 00:04:38:052 after 7707 milliseconds
LOVELY PROFESSIONAL UNIVERSITY 97