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}