I am learning to use ExectorService
to pool threads
and send out tasks. I have a simple program below
import java.util.concurrent.Execu
basically both calls execute,if u want future object you shall call submit() method here from the doc
public <T> Future<T> submit(Callable<T> task) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task);
execute(ftask);
return ftask;
}
public <T> Future<T> submit(Runnable task, T result) {
if (task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task, result);
execute(ftask);
return ftask;
}
as you can see java really has no way to start a thread other than calling run() method, IMO. since i also found that Callable.call()
method is called inside run()
method. hence if the object is callable it would still call run()
method, which inturn would call call()
method
from doc.
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
The difference is that execute
simply starts the task without any further ado, whereas submit
returns a Future
object to manage the task. You can do the following things with the Future
object:
cancel
method.get
.The Future
interface is more useful if you submit a Callable
to the pool. The return value of the call
method will be returned when you call Future.get
. If you don't maintain a reference to the Future
, there is no difference.