11import java .util .concurrent .ExecutorService ;
22import java .util .concurrent .Executors ;
3+ import java .util .concurrent .TimeUnit ;
34
45/**
56 * Created by rajeevkumarsingh on 09/05/17.
@@ -8,23 +9,42 @@ public class ExecutorsExample {
89 public static void main (String [] args ) {
910 System .out .println ("Inside : " + Thread .currentThread ().getName ());
1011
11- System .out .println ("Creating Executor Service... " );
12- ExecutorService executorService = Executors .newSingleThreadExecutor ( );
12+ System .out .println ("Creating Executor Service with a thread pool of Size 2 " );
13+ ExecutorService executorService = Executors .newFixedThreadPool ( 2 );
1314
14- System .out .println ("Creating a Runnable..." );
15- Runnable runnable = () -> {
16- System .out .println ("Inside : " + Thread .currentThread ().getName ());
15+ Runnable task1 = () -> {
16+ System .out .println ("Executing Task1 inside : " + Thread .currentThread ().getName ());
17+ try {
18+ TimeUnit .SECONDS .sleep (2 );
19+ } catch (InterruptedException ex ) {
20+ throw new IllegalStateException (ex );
21+ }
1722 };
1823
19- System .out .println ("Submit the task specified by the runnable to the executor service." );
20- executorService .submit (runnable );
24+ Runnable task2 = () -> {
25+ System .out .println ("Executing Task2 inside : " + Thread .currentThread ().getName ());
26+ try {
27+ TimeUnit .SECONDS .sleep (4 );
28+ } catch (InterruptedException ex ) {
29+ throw new IllegalStateException (ex );
30+ }
31+ };
2132
22- System .out .println ("Creating another Runnable..." );
23- Runnable runnable2 = () -> {
24- System .out .println ("Executing second task inside : " + Thread .currentThread ().getName ());
33+ Runnable task3 = () -> {
34+ System .out .println ("Executing Task3 inside : " + Thread .currentThread ().getName ());
35+ try {
36+ TimeUnit .SECONDS .sleep (3 );
37+ } catch (InterruptedException ex ) {
38+ throw new IllegalStateException (ex );
39+ }
2540 };
2641
27- System .out .println ("Submitting second runnable." );
28- executorService .submit (runnable2 );
42+
43+ System .out .println ("Submitting the tasks for execution..." );
44+ executorService .submit (task1 );
45+ executorService .submit (task2 );
46+ executorService .submit (task3 );
47+
48+ executorService .shutdown ();
2949 }
3050}
0 commit comments