Java Executor introduced in Java 1.5 and is part of java.util.concurrent API, it is an object which executes Runnable tasks similar to calling new Thread (Runnable).start () method. But it will not create new threads each time and reusing threads which are already created. See more about Executor. In this example we will create fixed thread pool to execute Runnable tasks.
java.util.concurrent.Executors providing the implementations for Executor interface, below are the main implementation to create thread pool.
Executors.newCachedThreadPool : Creates a thread pool of unlimited size, but if threads get freed up, they are reused
Executors.newFixedThreadPool : Create a thread pool of fixed size, if pool is exhausted, tasks must wait till a thread becomes free
Executors.newSingleThreadExecutor : Creates only a single thread, tasks are executed sequentially from the queue
Example
package com.pretech;import java.util.concurrent.Executor;import java.util.concurrent.Executors;public class ExecutorExample {public static void main(String[] args) {Executor executor = Executors.newFixedThreadPool(2);executor.execute(new Thread1());executor.execute(new Thread2());}}class Thread1 implements Runnable {public void run() {System.out.println("Thread one executing");}}class Thread2 implements Runnable {public void run() {System.out.println("Thread two executing");}}
Output
Thread one executing
Thread two executing
Reference : Java Concurrancy Framwork
No comments:
Post a Comment