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
  • No comments:

    Post a Comment