Friday, 30 December 2016

Java Tutorial: Java Threads (Thread pool in java | Java thread pool | Java thread pool tutorial_V5)


Click here to watch in Youtube :
https://www.youtube.com/watch?v=6Y4QjBBicyo&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge
Java Tutorial: Java Threads (Thread pool in java | Java thread pool | Java thread pool tutorial_V5) 
PrintCharTask.java
class PrintCharTask implements Runnable
{
    private char character;
    private int noOfTimes;

    PrintCharTask(char ch, int n)
    {
        character = ch;
        noOfTimes = n;
    }

    public void run()
    {
        for (int i = 0; i < noOfTimes; i++)
        {
            System.out.println(character + " ");
        }
    }
}
Threadpool.java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class Threadpool
{
    public static void main(String[] args)
    {
        System.out.println("Main Thread starts");
        ExecutorService threadExecutor = Executors.newFixedThreadPool(2);
        
        PrintCharTask taskl = new PrintCharTask('*', 5);
        PrintCharTask task2 = new PrintCharTask('S', 5);
        PrintCharTask task3 = new PrintCharTask('M', 5);
        PrintCharTask task4 = new PrintCharTask('N', 5);
        
        threadExecutor.execute(taskl);
        threadExecutor.execute(task2);
        threadExecutor.execute(task3);
        threadExecutor.execute(task4);
        /*
         * Tells the threadExecutor to shutdown. No new task
         * can be accepted but the existing task will
         * continue to finish.
         */
        threadExecutor.shutdown();
        /*
         * In order to ensure that the main thread finishes
         * last i.e. all tasks are finished before the main
         * thread terminates, we put the below while
         * statement.
         */
        while (!threadExecutor.isTerminated())
        {
        }
        System.out.println("\nMain Thread Ends");
    }
}
Output
Main Thread starts
* 
* 
* 
* 
* 
M 
M 
M 
M 
M 
N 
N 
N 
N 
N 
S 
S 
S 
S 
S 

Main Thread Ends

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/ThreadDemo_ThreadPool_V5_App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/ThreadDemo_ThreadPool_V5_App

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/d6d97a164a2acde3c2aa603063db8720e3eaea01/BasicJava/ThreadDemo_ThreadPool_V5_App/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Java Tutorial: Java Threads (Thread pool in java | Java thread pool | Java thread pool tutorial_V4)


    Click here to watch in Youtube :
    https://www.youtube.com/watch?v=opOyoZ1mTbE&list=UUhwKlOVR041tngjerWxVccw

    Click the below Image to Enlarge
    Java Tutorial: Java Threads (Thread pool in java | Java thread pool | Java thread pool tutorial_V4) 
    Java Tutorial: Java Threads (Thread pool in java | Java thread pool | Java thread pool tutorial_V4) 
    Java Tutorial: Java Threads (Thread pool in java | Java thread pool | Java thread pool tutorial_V4) 
    Java Tutorial: Java Threads (Thread pool in java | Java thread pool | Java thread pool tutorial_V4) 
    Java Tutorial: Java Threads (Thread pool in java | Java thread pool | Java thread pool tutorial_V4) 
    SimpleThreadPool.java
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class SimpleThreadPool
    {
    
        public static void main(String[] args)
        {
            ExecutorService executor = Executors.newFixedThreadPool(5);
            for (int i = 0; i < 10; i++)
            {
                Runnable runnableTask = new RunnableTask(" " + i);
                executor.execute(runnableTask);
            }
            executor.shutdown();
            while (!executor.isTerminated())
            {
            }
            System.out.println("Finished all threads");
        }
    }
    
    RunnableTask.java
    public class RunnableTask implements Runnable
    {
    
        private String taskNumber;
    
        public RunnableTask(String taskNumber)
        {
            this.taskNumber = taskNumber;
        }
    
        @Override
        public void run()
        {
            System.out.println(Thread.currentThread().getName()
                    + " Start. taskNumber = " + taskNumber);
            processCommand();
            System.out.println(Thread.currentThread().getName()
                    + " End of taskNumber =" + taskNumber);
        }
    
        private void processCommand()
        {
            try
            {
                Thread.sleep(5000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    
        @Override
        public String toString()
        {
            return this.taskNumber;
        }
    }
    
    Output
    pool-1-thread-2 Start. taskNumber =  1
    pool-1-thread-4 Start. taskNumber =  3
    pool-1-thread-3 Start. taskNumber =  2
    pool-1-thread-1 Start. taskNumber =  0
    pool-1-thread-5 Start. taskNumber =  4
    pool-1-thread-2 End of taskNumber = 1
    pool-1-thread-2 Start. taskNumber =  5
    pool-1-thread-4 End of taskNumber = 3
    pool-1-thread-4 Start. taskNumber =  6
    pool-1-thread-1 End of taskNumber = 0
    pool-1-thread-1 Start. taskNumber =  7
    pool-1-thread-5 End of taskNumber = 4
    pool-1-thread-5 Start. taskNumber =  8
    pool-1-thread-3 End of taskNumber = 2
    pool-1-thread-3 Start. taskNumber =  9
    pool-1-thread-4 End of taskNumber = 6
    pool-1-thread-2 End of taskNumber = 5
    pool-1-thread-3 End of taskNumber = 9
    pool-1-thread-1 End of taskNumber = 7
    pool-1-thread-5 End of taskNumber = 8
    Finished all threads
    
    
    Refer:
    https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html

    https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html

    Click the below link to download the code:
    https://sites.google.com/site/ramj2eev1/home/javabasics/ThreadDemo_ThreadPool_V3_App.zip?attredirects=0&d=1

    Github Link:
    https://github.com/ramram43210/Java/tree/master/BasicJava/ThreadDemo_ThreadPool_V3_App

    Bitbucket Link:
    https://bitbucket.org/ramram43210/java/src/d6d97a164a2acde3c2aa603063db8720e3eaea01/BasicJava/ThreadDemo_ThreadPool_V3_App/?at=master

    See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Java Tutorial: Java Threads (Thread pool executor | Thread pool in java | Java thread pool)

    Enjoying this Java & Concurrency tutorial?

    Subscribe to Ram N Java on YouTube

    Introduction

    Creating a new operating system thread for every incoming task in Java incurs significant memory and CPU overhead. A Thread Pool solves this problem by maintaining a pool of pre-created, reusable worker threads that execute tasks asynchronously from a blocking queue.

    In this guide, you will learn how the ThreadPoolExecutor and the java.util.concurrent.Executors framework simplify multithreading, optimize system resource utilization, and improve application throughput.

    1. Create a Runnable Task

    Define a task by implementing the Runnable interface to represent the work to be executed by worker threads:

    public class WorkerTask implements Runnable {
        private final String taskName;
    
        public WorkerTask(String taskName) {
            this.taskName = taskName;
        }
    
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " executing " + taskName);
            try {
                Thread.sleep(1000); // Simulate work
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            System.out.println(Thread.currentThread().getName() + " completed " + taskName);
        }
    }
      

    2. Initialize and Submit Tasks to ExecutorService

    Create a fixed-size thread pool using the Executors factory class and submit multiple tasks for execution:

    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class ThreadPoolDemo {
        public static void main(String[] args) {
            // Create a thread pool with 3 worker threads
            ExecutorService executor = Executors.newFixedThreadPool(3);
    
            // Submit 6 tasks to the pool
            for (int i = 1; i <= 6; i++) {
                executor.execute(new WorkerTask("Task-" + i));
            }
    
            // Shut down the executor gracefully after completion
            executor.shutdown();
        }
    }
      

    3. Key Advantages of Using Thread Pools

    • Resource Management: Prevents system degradation caused by creating too many threads simultaneously.
    • Better Performance: Eliminates thread creation and teardown latency by reusing existing threads.
    • Task Queueing: Safely buffers excess tasks in internal blocking queues until threads become available.

    Watch More Java Tutorials

    Blogger Metadata Settings: Labels: Java Concurrency, ThreadPoolExecutor, Java Multithreading, Thread Pool in Java, Core Java Tutorial Search Description (exactly 149 characters): Learn how Java ThreadPoolExecutor simplifies concurrency, reuses threads, and optimizes multithreaded task execution with practical Java code examples.

    Java Tutorial: Java Threads (Thread pool in java | Java thread pool | Java thread pool tutorial_V3)


    Click here to watch in Youtube :
    https://www.youtube.com/watch?v=Zm72Egs_s-Q&list=UUhwKlOVR041tngjerWxVccw

    Click the below Image to Enlarge
    Java Tutorial: Java Threads (Thread pool in java | Java thread pool | Java thread pool tutorial_V3)
    Java Tutorial: Java Threads (Thread pool in java | Java thread pool | Java thread pool tutorial_V3)
    Java Tutorial: Java Threads (Thread pool in java | Java thread pool | Java thread pool tutorial_V3)
    SimpleThreadPool.java
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class SimpleThreadPool
    {
    
        public static void main(String[] args)
        {
            ExecutorService executor = Executors.newFixedThreadPool(5);
            for (int i = 0; i < 10; i++)
            {
                Runnable runnableTask = new RunnableTask(" " + i);
                executor.execute(runnableTask);
            }
            executor.shutdown();
            while (!executor.isTerminated())
            {
            }
            System.out.println("Finished all threads");
        }
    }
    
    RunnableTask.java
    public class RunnableTask implements Runnable
    {
    
        private String taskNumber;
    
        public RunnableTask(String taskNumber)
        {
            this.taskNumber = taskNumber;
        }
    
        @Override
        public void run()
        {
            System.out.println(Thread.currentThread().getName()
                    + " Start. taskNumber = " + taskNumber);
            processCommand();
            System.out.println(Thread.currentThread().getName()
                    + " End of taskNumber =" + taskNumber);
        }
    
        private void processCommand()
        {
            try
            {
                Thread.sleep(5000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    
        @Override
        public String toString()
        {
            return this.taskNumber;
        }
    }
    
    Output
    pool-1-thread-2 Start. taskNumber =  1
    pool-1-thread-4 Start. taskNumber =  3
    pool-1-thread-3 Start. taskNumber =  2
    pool-1-thread-1 Start. taskNumber =  0
    pool-1-thread-5 Start. taskNumber =  4
    pool-1-thread-2 End of taskNumber = 1
    pool-1-thread-2 Start. taskNumber =  5
    pool-1-thread-4 End of taskNumber = 3
    pool-1-thread-4 Start. taskNumber =  6
    pool-1-thread-1 End of taskNumber = 0
    pool-1-thread-1 Start. taskNumber =  7
    pool-1-thread-5 End of taskNumber = 4
    pool-1-thread-5 Start. taskNumber =  8
    pool-1-thread-3 End of taskNumber = 2
    pool-1-thread-3 Start. taskNumber =  9
    pool-1-thread-4 End of taskNumber = 6
    pool-1-thread-2 End of taskNumber = 5
    pool-1-thread-3 End of taskNumber = 9
    pool-1-thread-1 End of taskNumber = 7
    pool-1-thread-5 End of taskNumber = 8
    Finished all threads
    
    
    Refer: 
    https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html

    https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html

    Click the below link to download the code:
    https://sites.google.com/site/ramj2eev1/home/javabasics/ThreadDemo_ThreadPool_V3_App.zip?attredirects=0&d=1

    Github Link:
    https://github.com/ramram43210/Java/tree/master/BasicJava/ThreadDemo_ThreadPool_V3_App

    Bitbucket Link:
    https://bitbucket.org/ramram43210/java/src/d6d97a164a2acde3c2aa603063db8720e3eaea01/BasicJava/ThreadDemo_ThreadPool_V3_App/?at=master

    See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Java Tutorial: Java Threads (Java Thread pool types | Thread pool in java | Java thread pool)


    Click here to watch in Youtube :
    https://www.youtube.com/watch?v=WUKmZxNt4Dw&list=UUhwKlOVR041tngjerWxVccw

    Click the below Image to Enlarge
    Java Tutorial: Java Threads (Java Thread pool types | Thread pool in java | Java thread pool) 
    Java Tutorial: Java Threads (Java Thread pool types | Thread pool in java | Java thread pool) 
    Java Tutorial: Java Threads (Java Thread pool types | Thread pool in java | Java thread pool) 
    Refer: 
    https://docs.oracle.com/javase/8/docs/api/index.html?java/util/concurrent/Executors.html

    https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html

    https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html

    See also:

  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Tuesday, 27 December 2016

    Java Tutorial: Java Threads (Cached Thread pool in java | Java cached thread pool)


    Click here to watch in Youtube :
    https://www.youtube.com/watch?v=wOqI-EeUWVE&list=UUhwKlOVR041tngjerWxVccw

    Click the below Image to Enlarge
    Java Tutorial: Java Threads (Cached Thread pool in java | Java cached thread pool) 
    Java Tutorial: Java Threads (Cached Thread pool in java | Java cached thread pool) 
    ThreadPoolTest.java
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    public class ThreadPoolTest
    {
        public static void main(String[] args)
        {
            int numOfCallableTasks = 4;
    
            ExecutorService executorService = Executors.newCachedThreadPool();
            CallableTask callableTasks[] = new CallableTask[numOfCallableTasks];
            Future<?> futures[] = new Future[numOfCallableTasks];
    
            for (int i = 0; i < numOfCallableTasks; i++)
            {
                callableTasks[i] = new CallableTask(i);
                futures[i] = executorService.submit(callableTasks[i]);
            }
            for (int i = 0; i < numOfCallableTasks; i++)
            {
                try
                {
                    System.out.println("Ending task : " + futures[i].get());
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
    
    CallableTask.java
    import java.util.concurrent.Callable;
    
    public class CallableTask implements Callable<Integer>
    {
        private int taskNumber;
    
        CallableTask(int taskNumber)
        {
            this.taskNumber = taskNumber;
        }
    
        public Integer call()
        {
            for (int i = 0; i <= 100; i += 20)
            {
                // Perform some work ...
                System.out.println(Thread.currentThread().getName()
                        + " taskNumber : " + taskNumber + ", percent complete: "
                        + i);
                try
                {
                    Thread.sleep((int) (Math.random() * 1000));
                }
                catch (InterruptedException e)
                {
                }
            }
            return (taskNumber);
        }
    }
    
    Output
    pool-1-thread-2 taskNumber : 1, percent complete: 0
    pool-1-thread-1 taskNumber : 0, percent complete: 0
    pool-1-thread-3 taskNumber : 2, percent complete: 0
    pool-1-thread-4 taskNumber : 3, percent complete: 0
    pool-1-thread-2 taskNumber : 1, percent complete: 20
    pool-1-thread-4 taskNumber : 3, percent complete: 20
    pool-1-thread-1 taskNumber : 0, percent complete: 20
    pool-1-thread-3 taskNumber : 2, percent complete: 20
    pool-1-thread-4 taskNumber : 3, percent complete: 40
    pool-1-thread-3 taskNumber : 2, percent complete: 40
    pool-1-thread-2 taskNumber : 1, percent complete: 40
    pool-1-thread-4 taskNumber : 3, percent complete: 60
    pool-1-thread-3 taskNumber : 2, percent complete: 60
    pool-1-thread-2 taskNumber : 1, percent complete: 60
    pool-1-thread-1 taskNumber : 0, percent complete: 40
    pool-1-thread-2 taskNumber : 1, percent complete: 80
    pool-1-thread-3 taskNumber : 2, percent complete: 80
    pool-1-thread-2 taskNumber : 1, percent complete: 100
    pool-1-thread-4 taskNumber : 3, percent complete: 80
    pool-1-thread-1 taskNumber : 0, percent complete: 60
    pool-1-thread-4 taskNumber : 3, percent complete: 100
    pool-1-thread-3 taskNumber : 2, percent complete: 100
    pool-1-thread-1 taskNumber : 0, percent complete: 80
    pool-1-thread-1 taskNumber : 0, percent complete: 100
    Ending task : 0
    Ending task : 1
    Ending task : 2
    Ending task : 3
    
    Click the below link to download the code:
    https://sites.google.com/site/ramj2eev1/home/javabasics/ThreadDemo_CachedThreadPool_App.zip?attredirects=0&d=1

    Github Link:
    https://github.com/ramram43210/Java/tree/master/BasicJava/ThreadDemo_CachedThreadPool_App

    Bitbucket Link:
    https://bitbucket.org/ramram43210/java/src/0fa116261fbf2fe2bc94946e6ef3f543aabbf896/BasicJava/ThreadDemo_CachedThreadPool_App/?at=master

    See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Java Tutorial: Java Threads (Thread pool in java | Java thread pool | Java thread pool tutorial_V2)


    Click here to watch in Youtube :
    https://www.youtube.com/watch?v=dy1uAsZOvC0&list=UUhwKlOVR041tngjerWxVccw

    Click the below Image to Enlarge
    Java Tutorial: Java Threads (Thread pool in java | Java thread pool | Java thread pool tutorial_V2) 
    Java Tutorial: Java Threads (Thread pool in java | Java thread pool | Java thread pool tutorial_V2) 
    Java Tutorial: Java Threads (Thread pool in java | Java thread pool | Java thread pool tutorial_V2) 
    Java Tutorial: Java Threads (Thread pool in java | Java thread pool | Java thread pool tutorial_V2) 
    ThreadPoolTest.java
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class ThreadPoolTest
    {
    
        public static void main(String[] args)
        {
            int numRunnableTask = 4;
            int threadPoolSize = 2;
    
            ExecutorService tpes = Executors.newFixedThreadPool(threadPoolSize);
    
            RunnableTask[] runnableTasks = new RunnableTask[numRunnableTask];
            for (int i = 0; i < numRunnableTask; i++)
            {
                runnableTasks[i] = new RunnableTask(i);
                tpes.execute(runnableTasks[i]);
            }
            tpes.shutdown();
        }
    }
    
    RunnableTask.java
    /*
     * Here is a runnable task. This task performs some work and
     * then periodically reports what percent of the work it has
     * completed:
     */
    
    public class RunnableTask implements Runnable
    {
        private int taskNumber;
    
        public RunnableTask(int taskNumber)
        {
            this.taskNumber = taskNumber;
        }
    
        public void run()
        {
            for (int i = 0; i <= 100; i += 20)
            {
                // Perform some work ...
                System.out.println(Thread.currentThread().getName()
                        + " = RunnableTask number: " + taskNumber
                        + ", percent complete: " + i);
                try
                {
                    Thread.sleep(3000);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
    
    Output
    pool-1-thread-1 = RunnableTask number: 0, percent complete: 0
    pool-1-thread-2 = RunnableTask number: 1, percent complete: 0
    pool-1-thread-1 = RunnableTask number: 0, percent complete: 20
    pool-1-thread-2 = RunnableTask number: 1, percent complete: 20
    pool-1-thread-2 = RunnableTask number: 1, percent complete: 40
    pool-1-thread-1 = RunnableTask number: 0, percent complete: 40
    pool-1-thread-1 = RunnableTask number: 0, percent complete: 60
    pool-1-thread-2 = RunnableTask number: 1, percent complete: 60
    pool-1-thread-1 = RunnableTask number: 0, percent complete: 80
    pool-1-thread-2 = RunnableTask number: 1, percent complete: 80
    pool-1-thread-1 = RunnableTask number: 0, percent complete: 100
    pool-1-thread-2 = RunnableTask number: 1, percent complete: 100
    pool-1-thread-2 = RunnableTask number: 2, percent complete: 0
    pool-1-thread-1 = RunnableTask number: 3, percent complete: 0
    pool-1-thread-2 = RunnableTask number: 2, percent complete: 20
    pool-1-thread-1 = RunnableTask number: 3, percent complete: 20
    pool-1-thread-1 = RunnableTask number: 3, percent complete: 40
    pool-1-thread-2 = RunnableTask number: 2, percent complete: 40
    pool-1-thread-1 = RunnableTask number: 3, percent complete: 60
    pool-1-thread-2 = RunnableTask number: 2, percent complete: 60
    pool-1-thread-2 = RunnableTask number: 2, percent complete: 80
    pool-1-thread-1 = RunnableTask number: 3, percent complete: 80
    pool-1-thread-1 = RunnableTask number: 3, percent complete: 100
    pool-1-thread-2 = RunnableTask number: 2, percent complete: 100
    
    Refer: 
    https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html

    https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html

    Click the below link to download the code:
    https://sites.google.com/site/ramj2eev1/home/javabasics/ThreadDemo_ThreadPool_V2_App.zip?attredirects=0&d=1

    Github Link:
    https://github.com/ramram43210/Java/tree/master/BasicJava/ThreadDemo_ThreadPool_V2_App

    Bitbucket Link:
    https://bitbucket.org/ramram43210/java/src/0fa116261fbf2fe2bc94946e6ef3f543aabbf896/BasicJava/ThreadDemo_ThreadPool_V2_App/?at=master

    See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Tutorials