Thread
creation is not comes for free. It includes overhead of creation of
thread, assigning a stack to it, and destroy once thread done with
its execution. Instead of using frequent short lived threads, use
Thread pooling. You can create a pool of threads and each thread in the
pool is waiting for a task to execute. When a task is assigned to a
thread in the thread pool, it starts executing the task, once it
finishes the task execution, instead of destroying, it go back to the
thread pool and waits for another task to execute. With this approach
no need to create a new thread for every new task.
Below
example demonstrates the use of Thread pools.
WorkerThread.java
class WorkerThread implements Runnable{ String taskName; WorkerThread(String taskName){ this.taskName = taskName; } public void run(){ try{ Thread t1 = Thread.currentThread(); System.out.println(t1.getName() + " executing the task " + taskName); t1.sleep(1000); System.out.println(t1.getName() + " completed the task " + taskName); } catch(Exception e){ System.out.println(e); } } }
SimpleThreadPool.java
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; class SimpleThreadPool{ public static void main(String args[]){ ExecutorService executors = Executors.newFixedThreadPool(5); WorkerThread tasks[] = new WorkerThread[10]; for(int i=0; i<10; i++){ tasks[i] = new WorkerThread("task" + i); executors.execute(tasks[i]); } executors.shutdown(); } }
Sample
Output
pool-1-thread-1 executing the task task0 pool-1-thread-3 executing the task task2 pool-1-thread-4 executing the task task3 pool-1-thread-5 executing the task task4 pool-1-thread-2 executing the task task1 pool-1-thread-1 completed the task task0 pool-1-thread-3 completed the task task2 pool-1-thread-3 executing the task task5 pool-1-thread-1 executing the task task6 pool-1-thread-2 completed the task task1 pool-1-thread-2 executing the task task7 pool-1-thread-5 completed the task task4 pool-1-thread-5 executing the task task8 pool-1-thread-4 completed the task task3 pool-1-thread-4 executing the task task9 pool-1-thread-3 completed the task task5 pool-1-thread-1 completed the task task6 pool-1-thread-2 completed the task task7 pool-1-thread-5 completed the task task8 pool-1-thread-4 completed the task task9
WorkerThread
is a class that implements Runnable interface. Created 10 Runnable
tasks and assign it to the thread pool to execute.
ExecutorService
executors = Executors.newFixedThreadPool(5);
Above
statement creates a fixed thread pool of size 5, I.e, it has 5
threads in it waiting for tasks to execute.
executors.execute(tasks[i])
executes
the given task, by assigning it ti the thread in the Task shared
pool. If all the thread are busy in executing other tasks, then it
waits until some thread is free to run this task.
executors.shutdown()
Once
all the tasks assigned to the threads in the thread pool finished,
then it initialize orderly shutdown of threads.
No comments:
Post a Comment