Saturday, 10 June 2017

Java Tutorial: Java Threads (Thread pool in java | Java thread pool | Java thread pool tutorial_V1) ~ foundjava


Click here to watch in Youtube :

Click the below Image to Enlarge
Java Tutorial: Java Threads (Thread pool in java | Java thread pool | Java thread pool tutorial_V1) 
Java Tutorial: Java Threads (Thread pool in java | Java thread pool | Java thread pool tutorial_V1) 
Java Tutorial: Java Threads (Thread pool in java | Java thread pool | Java thread pool tutorial_V1) 
ThreadPoolDemo.java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolDemo
{

    public static void main(String[] args)
    {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 10; i++)
        {
            WorkerThread workerThread = new WorkerThread("Hello " + i);
            executorService.execute(workerThread);
        }
        executorService.shutdown();
        while (!executorService.isTerminated())
        {
            
        }
        System.out.println("Finished all threads");
    }
}
WorkerThread.java
class WorkerThread implements Runnable
{
    private String message;

    public WorkerThread(String message)
    {
        this.message = message;
    }

    public void run()
    {
        System.out.println(Thread.currentThread().getName()
                + " (Start) message = " + message);
        processmessage();
        System.out.println(Thread.currentThread().getName() + " (End)");
    }

    private void processmessage()
    {
        try
        {
            Thread.sleep(2000);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }

}
Output
pool-1-thread-1 (Start) message = Hello 0
pool-1-thread-2 (Start) message = Hello 1
pool-1-thread-3 (Start) message = Hello 2
pool-1-thread-2 (End)
pool-1-thread-2 (Start) message = Hello 3
pool-1-thread-1 (End)
pool-1-thread-1 (Start) message = Hello 4
pool-1-thread-3 (End)
pool-1-thread-3 (Start) message = Hello 5
pool-1-thread-2 (End)
pool-1-thread-2 (Start) message = Hello 6
pool-1-thread-1 (End)
pool-1-thread-1 (Start) message = Hello 7
pool-1-thread-3 (End)
pool-1-thread-3 (Start) message = Hello 8
pool-1-thread-2 (End)
pool-1-thread-2 (Start) message = Hello 9
pool-1-thread-1 (End)
pool-1-thread-3 (End)
pool-1-thread-2 (End)
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:

CLICK HERE

No comments:

Post a Comment