1import java.util.concurrent.Executors;
2import java.util.concurrent.ThreadPoolExecutor;
3import java.util.concurrent.TimeUnit;
4
5public class TestThread {
6
7 public static void main(final String[] arguments) throws InterruptedException {
8 ThreadPoolExecutor executor = (ThreadPoolExecutor)Executors.newCachedThreadPool();
9
10 //Stats before tasks execution
11 System.out.println("Largest executions: "
12 + executor.getLargestPoolSize());
13 System.out.println("Maximum allowed threads: "
14 + executor.getMaximumPoolSize());
15 System.out.println("Current threads in pool: "
16 + executor.getPoolSize());
17 System.out.println("Currently executing threads: "
18 + executor.getActiveCount());
19 System.out.println("Total number of threads(ever scheduled): "
20 + executor.getTaskCount());
21
22 executor.submit(new Task());
23 executor.submit(new Task());
24
25 //Stats after tasks execution
26 System.out.println("Core threads: " + executor.getCorePoolSize());
27 System.out.println("Largest executions: "
28 + executor.getLargestPoolSize());
29 System.out.println("Maximum allowed threads: "
30 + executor.getMaximumPoolSize());
31 System.out.println("Current threads in pool: "
32 + executor.getPoolSize());
33 System.out.println("Currently executing threads: "
34 + executor.getActiveCount());
35 System.out.println("Total number of threads(ever scheduled): "
36 + executor.getTaskCount());
37
38 executor.shutdown();
39 }
40
41 static class Task implements Runnable {
42
43 public void run() {
44
45 try {
46 Long duration = (long) (Math.random() * 5);
47 System.out.println("Running Task! Thread Name: " +
48 Thread.currentThread().getName());
49 TimeUnit.SECONDS.sleep(duration);
50 System.out.println("Task Completed! Thread Name: " +
51 Thread.currentThread().getName());
52 } catch (InterruptedException e) {
53 e.printStackTrace();
54 }
55 }
56 }
57}
1
2package com.journaldev.threadpool;
3
4public class WorkerThread implements Runnable {
5
6 private String command;
7
8 public WorkerThread(String s){
9 this.command=s;
10 }
11
12 @Override
13 public void run() {
14 System.out.println(Thread.currentThread().getName()+" Start. Command = "+command);
15 processCommand();
16 System.out.println(Thread.currentThread().getName()+" End.");
17 }
18
19 private void processCommand() {
20 try {
21 Thread.sleep(5000);
22 } catch (InterruptedException e) {
23 e.printStackTrace();
24 }
25 }
26
27 @Override
28 public String toString(){
29 return this.command;
30 }
31}
32