The difference between submit and execute in Executorservice

Source: Internet
Author: User

After Java5, the concurrency thread has changed radically, and the most important thing is a new stack of APIs to start, schedule, and manage threads. After the JAVA5, through
Executor to start the line turndown with the thread start () better. In the new feature, it is easy to control the threading startup, execution, and shutdown processes, and it is easy to use the thread pool's special
Of

First, create a task

A task is a class that implements the Runnable interface.

The real run method is available when you create it.

II. implementation of the mandate

The task is performed through the Java.util.concurrent.ExecutorService interface object, which is created through a static method of the tool class java.util.concurrent.Executors.

Executors factory and utility methods for the Executor, Executorservice, Scheduledexecutorservice, Threadfactory, and callable classes defined in this package.

Executorservice provides methods for managing termination, as well as a way to generate a future for tracking one or more asynchronous task execution states. Can close
Executorservice, which will cause it to stop accepting new tasks. When it is closed, the execution is terminated, no tasks are executing, no tasks are waiting to be executed, and the new
Works

Executorservice.execute (New testrunnable ());

1. Create Executorservice

Created using the static method of the tool class java.util.concurrent.Executors.

Executors factory and utility methods for the Executor, Executorservice, Scheduledexecutorservice, Threadfactory, and callable classes defined in this package.

For example, to create an instance of Executorservice, Executorservice is actually a management tool for a thread pool:

Executorservice Executorservice = Executors.newcachedthreadpool ();

Executorservice Executorservice = Executors.newfixedthreadpool (3);

Executorservice Executorservice = Executors.newsinglethreadexecutor ();

2. Add the task to the thread to execute

When adding a task to the thread pool, the thread pool will create one for each task, which will be executed automatically at a later point in time.

Third, close the execution service object

Executorservice.shutdown ();

Iv. Comprehensive Examples

Package concurrent;

Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;

/**
* Created by IntelliJ idea.
*
* @author leizhimin 2008-11-25 14:28:59
*/
Publicclass Testcachedthreadpool {
Publicstaticvoid Main (string[] args) {
Executorservice Executorservice = Executors.newcachedthreadpool ();
Executorservice Executorservice = Executors.newfixedthreadpool (5);

Executorservice Executorservice = Executors.newsinglethreadexecutor ();

for (int i = 0; i < 5; i++) {
Executorservice.execute (New testrunnable ());
System.out.println ("************* a" + i + "*************");
}
Executorservice.shutdown ();
}
}

Class Testrunnable implements Runnable {
Publicvoid Run () {
System.out.println (Thread.CurrentThread (). GetName () + "thread was called. ");
while (true) {
try {
Thread.Sleep (5000);
System.out.println (Thread.CurrentThread (). GetName ());
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
}

Operation Result:

A0 *************
A1 *************
The pool-1-thread-2 thread was called.
A2 *************
The pool-1-thread-3 thread was called.
The pool-1-thread-1 thread was called.
A3 *************
A4 *************
The pool-1-thread-4 thread was called.
The pool-1-thread-5 thread was called.
Pool-1-thread-2
Pool-1-thread-1
Pool-1-thread-3
Pool-1-thread-5
Pool-1-thread-4
Pool-1-thread-2
Pool-1-thread-1
Pool-1-thread-3
Pool-1-thread-5
Pool-1-thread-4
......

V. Get the return value of a task's execution

After Java5, the task is divided into two classes: one is the class that implements the Runnable interface, and the other is the class that implements the callable interface. Both can be
Executorservice executes, but the runnable task does not return a value, and the callable task has a return value. and the call () method of callable only
Can be executed through the Executorservice (<T> Task) method, and returns a <t><t>
Waiting for the completion of the future.

public interface callable<v>
A task that returns the result and may throw an exception. The implementing person defines a method called call without any parameters.
The callable interface is similar in that both are designed for classes whose instances might be executed by another thread. However, Runnable does not return a result and cannot throw a checked exception.
class contains some practical methods for converting from other ordinary forms to callable classes.

The call () method in callable is similar to the runnable run () method, where the former has a return value and the latter does not.

When a callable object is passed to the Executorservice's Submit method, the call method executes automatically on a thread and returns the execution result to the future object.

Similarly, the Runnable object is passed to the Executorservice's Submit method, and the Run method executes automatically on a thread and returns the execution result of the future object, but calls the Get method on the future object, which returns NULL.

Unfortunately, in the Java API documentation, this piece of introduction is very confusing, it is estimated that the translator is not clear about it. Or a comment that is not in place. Let's look at an example:

Import java.util.ArrayList;
Import java.util.List;
Import java.util.concurrent.*;

/**
* Callable Interface Test
*
* @author leizhimin 2008-11-26 9:20:13
*/
Publicclass Callabledemo {
Publicstaticvoid Main (string[] args) {
Executorservice Executorservice = Executors.newcachedthreadpool ();
list<future<string>> resultlist = new arraylist<future<string>> ();

Create 10 of tasks and execute
for (int i = 0; i < i++) {
Use Executorservice to perform callable types of tasks and save the results in future variables
future<string> future = Executorservice.submit (new Taskwithresult (i));
To store task execution results in a list
Resultlist.add (future);
}

Traverse the results of a task
for (future<string> fs:resultlist) {
try {
System.out.println (Fs.get ()); Print the results of each thread (Task) execution
} catch (Interruptedexception e) {
E.printstacktrace ();
} catch (Executionexception e) {
E.printstacktrace ();
} finally {
Starts a sequential shutdown, performs a previously submitted task, but does not accept new tasks. If it is already closed, the call has no other effect.
Executorservice.shutdown ();
}
}
}
}

Class Taskwithresult implements Callable<string> {
Privateint ID;

public taskwithresult (int id) {
This.id = ID;
}

/**
* The specific process of the task, once the task is passed to Executorservice's Submit method, the method is automatically executed on a thread.
*
* @return
* @throws Exception
*/
Public String Call () throws Exception {
System.out.println ("Call () method is automatically called, Work!!!" "+ Thread.CurrentThread (). GetName ());
A simulated time-consuming operation
for (int i = 999999; i > 0; i--);
The return "call () method is called automatically, and the result of the task is:" + ID + "+ thread.currentthread (). GetName ();
}
}

Operation Result:
Call () method is automatically called, Work!!! Pool-1-thread-1
Call () method is automatically called, Work!!! Pool-1-thread-3
Call () method is automatically called, Work!!! Pool-1-thread-4
Call () method is automatically called, Work!!! Pool-1-thread-6
Call () method is automatically called, Work!!! Pool-1-thread-2
Call () method is automatically called, Work!!! Pool-1-thread-5
The call () method is called automatically, and the result of the task is: 0 pool-1-thread-1
The call () method is called automatically, and the result of the task is: 1 pool-1-thread-2
Call () method is automatically called, Work!!! Pool-1-thread-2
Call () method is automatically called, Work!!! Pool-1-thread-6
Call () method is automatically called, Work!!! Pool-1-thread-4
The call () method is called automatically, and the result of the task is: 2 pool-1-thread-3
Call () method is automatically called, Work!!! Pool-1-thread-3
The call () method is called automatically, and the result of the task is: 3 pool-1-thread-4
The call () method is called automatically, and the result of the task is: 4 pool-1-thread-5
The call () method is called automatically, and the result of the task is: 5 pool-1-thread-6
The call () method is called automatically, and the result of the task is: 6 pool-1-thread-2
The call () method is called automatically, and the result of the task is: 7 pool-1-thread-6
The call () method is called automatically, and the result of the task is: 8 pool-1-thread-4
The call () method is called automatically, and the result of the task is: 9 pool-1-thread-3

Process finished with exit code 0
/////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////

Because the Execute method has been used before, recently there is a case that requires the Submit method, so the following is studied.

Three differences:

1, the received parameters are different

2. Submit has a return value, and execute has no

Method Submit extends base method Executor.execute by creating and
Returning a future so can be used to cancel execution and/or wait for
Completion.

Using the example of the return value, for example, I have a lot of tasks to do validation, I want all the tasks to be executed, and then each task tells me the result of its execution, whether it succeeds or fails, and if it fails, what the reason is. Then I can synthesize all the reasons for failure and send them to the caller.

Personally think that the cancel execution is not very useful, there is little need to cancel execution.

And the greatest use should be the 2nd.

3, submit convenient exception processing

There is a difference if looking at exception handling. If your tasks throws an exception and if it is submitted with execute this
Exception'll go to the uncaught exception handler (when you don ' t
Have provided one explicitly, the default one would just print the stack
Trace to System.err). If you submitted the task with a submit any thrown exception, checked or not, was then part of the task's return status. For a task that is submitted with submit and that terminates with an exception, the Future.get would rethrow this exceptio N, wrapped in an executionexception.

This means that if you throw checked or unchecked exception in your task, and you want callers outside to be able to perceive these exception and make timely processing, then you need to use submit, Throws an exception by capturing Future.get.

The difference between submit and execute in Executorservice

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.