Java Reference
In-Depth Information
public class MyTask implements Runnable {
public void run() {
// Task processing logic goes here
}
}
You create tasks as follows:
MyTask task1 = new MyTask();
MyTask task2 = new MyTask();
MyTask task3 = new MyTask();
To execute the tasks, you use threads as follows:
Thread t1 = new Thread(task1);
Thread t2 = new Thread(task2);
Thread t3 = new Thread(task3);
t1.start();
t2.start();
t3.start();
If you want to get the result of a task execution, you have to write additional code. You may notice that managing
tasks as described above is difficult, if not impossible. There is another aspect of tasks execution that is very important:
how many threads should be created to execute a group of tasks? One approach would be to create a thread per task.
Creating a thread per task has the following disadvantages:
Creating and destroying threads has overhead and it takes time, which in turn delays the start
of the execution of the tasks.
Each thread consumes resources. If the number of threads is more than the available CPUs,
other threads will be sitting idle and will be consuming resources.
Each platform has a limit of how many maximum threads it can support. If an application
exceeds that limit, it may even crash!
Another approach is to create one thread and let it handle the execution of all tasks. This is another extreme case,
which has the following disadvantages:
Having one thread executing all tasks makes it a sequential executor.
This policy is deadlock-prone if one task submits another task and it depends on the result of
the task it has submitted.
If you have long-running tasks, other tasks waiting for their execution seem to be unresponsive
because of the long time it will take to start the pending tasks.
The executor framework attempts to solve all of these aspects of a task execution. The framework provides a
way to separate task submission from task execution. You create a task and submit it to an executor. The executor
takes care of the execution details of the task. It provides configurable policies to control many aspects of the
task execution.
Search WWH ::




Custom Search