-
Notifications
You must be signed in to change notification settings - Fork 294
/
Copy pathThreadPoolWithRunnable.java
44 lines (33 loc) · 1.19 KB
/
ThreadPoolWithRunnable.java
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
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolWithRunnable {
//Executor maintains thread pool to improve application performance by avoiding the continuous spawning of threads.
//It executes the task bu running necessary threads from the pool.
static final int MAX_T = 10; //Thread Pool Size
static int i = 0;
public static void main(String abc[]) {
Runnable r1 = new Thread_1();
// creates a thread pool with MAX_T no. of threads for concurrent execution
ExecutorService pool = Executors.newFixedThreadPool(MAX_T);
// passes the Task objects to the pool to execute
for (i = 0; i < 20; i++) {
pool.execute(r1); //Executes by picking non-running thread from the pool.
}
pool.shutdown();
}
}
class Thread_1 implements Runnable {
private int name;
public Thread_1() {}
public void run() {
try {
System.out.println(
"Thread " +
java.lang.Thread.currentThread().getId() +
" is running"
);
} catch (Exception e) {
e.printStackTrace();
}
}
}