In Java concurrent programming, if you do not need to monitor the results of the program running, then you can use the Runnable interface, directly to the thread pool can be thrown. Because the Runnabale interface does not have a return value.
E.g.1 public class TestRun implements runnable{
@Override
public void Run () {
...................................
}
}
When you need to monitor a thread's running results, you can use the future and callable interfaces. For example, check that the program is running beyond the specified time because the thread belongs to the asynchronous computing model and cannot get the results of execution directly from other threads. The definition of callable is usually as follows:
E.g.2 public class Testcall implements Callable<integer>//Returns the result of an integer value and may throw an exception if the result cannot be computed.
{
@Override
Public Integer Call () {The definition of the//return value is consistent with the definition type of the Callalbe return value
Integer Ret=integer.min_value;
................................
return ret;
}
}
Future can monitor where the target thread invokes call, and when you call the future Get () method to obtain the result, the current thread begins to block, and the direct call method ends the return result.
The following example uses Executorservice to use future to monitor callable interfaces, and Executorservice inherits from executor, providing a way to manage termination. And a way to generate future for tracking one or more asynchronous task execution conditions.
E.g.3
Class Testmonitorfuture implements runnable{
Private Executorservice ThreadPool = Executors.newcachedthreadpool (); Creating a thread pool
Monitor monitorobject = new Monitor (); Monitoring procedures
Monitorobject.start (); Start the monitoring process
Threadpool.submit (New Testcall ())//Submit a callable task with a return value for execution, returning a future that represents the pending result of the task. The future Get method HWI Returns the result of the//task upon successful completion. You can use result = Exec.submit (acallable) If you want to immediately block the wait for a task.
The Testcall task is placed in the monitoring procedure so that the monitoring procedure can use Future.get ().
}
In this example, an additional monitoring procedure is used to monitor the operation results of the Callabe interface.
Future's working principle can refer to: http://blog.csdn.net/yangyan19870319/article/details/6093481