-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTestFixedThreadPool.java
More file actions
70 lines (59 loc) · 1.91 KB
/
Copy pathTestFixedThreadPool.java
File metadata and controls
70 lines (59 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package inverview.executor;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestFixedThreadPool {
// Maximum number of threads in thread pool
private static final int MAX_T = 3;
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(MAX_T);
Runnable r1 = new Task("task 1");
Runnable r2 = new Task("task 2");
Runnable r3 = new Task("task 3");
Runnable r4 = new Task("task 4");
Runnable r5 = new Task("task 5");
/*
* As seen in the execution of the program, the task 4 or task 5 are executed
* only when a thread in the pool becomes idle. Until then, the extra tasks are
* placed in a queue.
*/
pool.execute(r1);
pool.execute(r2);
pool.execute(r3);
pool.execute(r4);
pool.execute(r5);
// pool shutdown ( Step 4)
pool.shutdown();
}
}
class Task implements Runnable {
private String name;
public Task(String s) {
name = s;
}
// Prints task name and sleeps for 1s
// This Whole process is repeated 5 times
public void run() {
try {
for (int i = 0; i <= 5; i++) {
if (i == 0) {
Date d = new Date();
SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss");
System.out.println("Initialization Time for" + " task name - " + name + " = " + ft.format(d));
// prints the initialization time for every task
} else {
Date d = new Date();
SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss");
System.out.println("Executing Time for task name - " + name + " = " + ft.format(d));
// prints the execution time for every task
}
Thread.sleep(1000);
}
System.out.println(name + " complete");
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}