Starting a task before Java 5.0 is done by invoking the start () method of the thread class, where the task's delivery and execution are simultaneous, and if you want to schedule the execution of the task or control the number of threads executing concurrently, you need to write additional code. The 5.0-LANE provides a new task-execution architecture that allows you to easily schedule and control the execution of tasks, and create a thread pool similar to the database connection pool to perform tasks. This architecture consists primarily of three interfaces and their corresponding concrete classes. These three interfaces are executor, Executorservice, Scheduledexecutorservice, let's use a graph to show their relationships:
The left side of the diagram is the interface, and the right side of the graph is the concrete class of these interfaces. Note that the executor is not directly implemented.
Executor interface: is used to perform runnable tasks, it defines only one method:
Execute (Runnable command): Performing tasks of type ruannable
Executorservice Interface: Executorservice inherits the Executor method and provides services to perform callable tasks and abort tasks, which are defined in the following ways:
Submit (Task): can be used to submit callable or runnable tasks and return future objects that represent this task
InvokeAll (Collection of tasks): Collection of batch tasks, and returns a collection of future objects representing these tasks
shutdown (): Closes a service after a committed task is completed and no longer accepts new tasks
Shutdownnow (): Stops all executing tasks and closes the service.
isterminated (): Tests whether all tasks have been executed.
IsShutDown (): Test if the executorservice has been turned off
The Scheduledexecutorservice interface, based on Executorservice, Scheduledexecutorservice provides the ability to perform tasks on a schedule, which provides the following methods:
Schedule (Task, Initdelay): Schedule the submitted callable or runnable tasks to execute after the specified time in Initdelay.
scheduleatfixedrate (): Schedule the submitted runnable tasks to be repeated at specified intervals
Schedulewithfixeddelay (): Schedule the submitted runnable task to repeat after each execution, waiting for the time specified by delay.
the important Executors class
Although the interfaces mentioned above have a specific class of implementations, it is necessary to note that the executors is a class, not a executor plural form, in order to facilitate Java 5.0 's recommendation to use the Executors tool class to get the specific object of the executor interface. Executors provides some of the following static methods:
Callable (Runnable Task):Translating runnable tasks into callable tasks
Newsinglethreadexecutor:Produces a Executorservice object with only one thread available to perform the task, and if more than one task, the task is executed sequentially.
Newcachedthreadpool ():Generates a Executorservice object with a thread pool, and the size of the thread pool is adjusted as needed, and the thread is returned to the thread pool to perform the next task when it finishes the task.
newfixedthreadpool (int poolsize):Produces a Executorservice object with a thread pool of size poolsize, and if the number of tasks is greater than poolsize, the task is executed sequentially in a queue.
Newsinglethreadscheduledexecutor:Generates a Scheduledexecutorservice object that has a thread pool size of 1 and, if more than one task, the task is executed sequentially.
newscheduledthreadpool (int poolsize):Produces a Scheduledexecutorservice object, which has a thread pool size of poolsize, and if the number of tasks is greater than poolsize, the task waits in a queue for execution
An example is provided:
apply executors to create thread pool
Sometimes you need to build a bunch of thread to perform small tasks, but frequent thread creation is sometimes a cost because thread creation must interact with the operating system, and if you can create a thread pool to manage these small thread and reuse it, It will be a way to improve system performance.
You can use executors to create a thread pool,executors There are several static methods, listed below:
| Method |
Description |
| Newcachedthreadpool |
Create a thread that can be quickly fetched, each thread preset can be idle for 60 seconds |
|
Newfixedthreadpool |
Include a fixed number of thread |
|
Newsinglethreadexecutor |
There is only one thread, sequential execution of each task assigned to it |
| Newscheduledthreadpool |
Thread that can be arranged |
| Newsinglethreadscheduledexecutor |
Thread of Single Schedule |
To take a simple example, the following program uses the Newfixedthreadpool method to create the thread pool, which includes five thread that can be reused, you can specify the Runnable object to give it, the program will produce 10 runnable objects, Since there are only five thread available in the thread pool, the five runnable that were created later must wait for free thread to be executed:
Executordemo.java
Copy Code code as follows:
Package onlyfun.caterpillar;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
public class Executordemo {
public static void Main (string[] args) {
Executorservice service = Executors.newfixedthreadpool (5);
for (int i = 0; i < i++) {
Final int count = i;
Service.submit
(New Runnable () {
public void Run () {
System.out.println (count);
try {
Thread.Sleep (2000);
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
});
}
Service.shutdown (); Finally remember to close the thread pool
}
}
The Submit () method also accepts an object that implements the callable interface and returns the future object at the end, which results in a return of callable execution. If you want to use executors for scheduling, such as scheduling a job after 30 seconds:
Copy Code code as follows:
Scheduledexecutorservice Scheduler = Executors.newsinglethreadscheduledexecutor ();
Scheduler.schedule (New Runnable () {
public void Run () {
Scheduling work
}
},
, timeunit.seconds);
or schedule a job for 5 seconds, and then perform every 30 seconds:
Copy Code code as follows:
Final Scheduledfuture future = scheduler.scheduleatfixedrate (new Runnable () {
public void Run () {
Scheduling work
System.out.println ("T");
}
},
0, 5, timeunit.seconds);
Schedule 60 seconds to cancel future
Scheduler.schedule (New Runnable () {
public void Run () {
Future.cancel (FALSE);
}
}, Timeunit.seconds);
As shown above, to cancel the scheduling task, you can call the Scheduledfuture Cancel () method.