Ans)
-
Sample Img 20
Java Thread Executor is simple Java
Framework which is based on "Master-Slave
architectural design pattern" allows us to perform
multiple tasks asynchronously
for better performance. In
general Tasks are logical units of work, and threads
are
a mechanism by which tasks can run asynchronously. Also this
Framework
takes the Overhead of managing the Threads and
its priorities and frees you from them.
By
decoupling the task submission from execution, we can easily
change or specify
execution policies, such as
• execution order, how many tasks are allowed to run
concurrently
and how many are queued,
etc.
Here is the Simple Example :
Step 1 : Create an
"ExecutorService" with Number of Thread you
would like to have.
//Let us
start the Worked Threads
ExecutorService executor =
Executors.newFixedThreadPool(NTHREDS);
Step 2 : Create a
Worker Thread, which actually perform the given task, your Worker
Thread perform different tasks,
public
class EmailSender implements Runnable {
String message;
EmailSender (String message) {
this.message = message;
}
public void run() {
try {
sendEmail(message);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void
sendEmail(String message2) {
System.out.println("Sending Email" +
message);
}
}
Step 3
: Assign these Tasks to Executor
//Let us start the Worked Threads
ExecutorService executor =
Executors.newFixedThreadPool(NTHREDS);
for (int i = 0; i < 6; i++) {
DateRange dateRange = new DateRange();
Runnable worker = new BatchRunnable(dateRange);
executor.execute(worker);
}
Step 4: Terminate
the Executor by invoking the LifeCycle methods
// This will make the executor accept no new threads
// and finish all existing threads in the queue
executor.shutdown();
// Wait until all threads are finish
while (!executor.isTerminated()) {
}
Back to top