Recently in the study of the Android Asynctask source code, found that a lot of Java SE multithreading knowledge, so go back to the JDK documentation Review of Java multithreading related knowledge, make a note easy to find later.
Introduction to callable in the JDK API
The callable interface is similar to Runnable, both of which 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 .
We can submit a runnable or callable task by Executorservice The Submit method, and return a future object.
Future Represents the result of an asynchronous computation, we can either get the result of the calculation by Future the object or cancel the task in progress.
The following is an example to compare the differences between runnable and callable.
Package com.example.test.callable;
Import java.util.concurrent.Callable;
Import java.util.concurrent.ExecutionException;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.Future;
public class Callabletest {/** * @param args */public static void main (string[] args) {//testrunnable ();
Testcallable ();
private static void Testcallable () {Executorservice pool = Executors.newfixedthreadpool (3);
Calculatecallable Task1 = new calculatecallable (0);
Calculatecallable task2 = new calculatecallable (1);
Calculatecallable task3 = new calculatecallable (3); try {//Commit and execute the task, the task starts with a Future object,//If you want the result of a task execution or an exception to manipulate the Future object future<integer> future1 = Pool.s
Ubmit (TASK1);
Gets the result of the first task, and if the Get method is invoked, the current thread waits until the task is finished executing System.out.println ("Task1 get:" + future1.get ());
future<integer> Future2 = Pool.submit (TASK2);
System.out.println ("Task2 get:" + Future2.get (2000, Timeunit.milliseconds));
Wait 5 seconds, then stop the second task, because the second task is an infinite loop thread.sleep (8000);
System.out.println ("Task2 Cancel:" + Future2.cancel (true));
future<integer> future3 = Pool.submit (TASK3);
System.out.println ("Task3 get:" + future3.get ());
catch (Interruptedexception e) {e.printstacktrace ();
catch (Executionexception e) {e.printstacktrace ();
//Stop Task Execution Service Pool.shutdownnow ();
private static void Testrunnable () {calculaterunnable Task1 = new calculaterunnable (0);
Calculaterunnable task2 = new calculaterunnable (1);
Calculaterunnable task3 = new calculaterunnable (3);
Executorservice pool = Executors.newfixedthreadpool (3);
try {future<?> future1 = Pool.submit (TASK1);
System.out.println ("Task1 get:" + future1.get ());
future<?> Future2 = Pool.submit (TASK2);
System.out.println ("Task2 get:" + future2.get ());
Wait 5 seconds, then stop the second task Thread.Sleep (8000); System.out.println ("Task2 Cancel:" + FutuRe2.cancel (true));
future<?> future3 = Pool.submit (TASK3);
System.out.println ("Task3 get:" + future3.get ());
catch (Interruptedexception e) {e.printstacktrace ();
catch (Executionexception e) {e.printstacktrace ();
//Stop Task Execution Service Pool.shutdownnow ();
public static class Calculatecallable implements callable<integer> {private int param =-1;
public calculatecallable (int param) {this.param = param; @Override public Integer Call () throws Exception {if (This.param = 0) {System.out.println ("no loop*****
"+ param);
return 0; else if (This.param = = 1) {//If flag value is 1, do an infinite loop try {while (true) {System.out.println ("while loo
ping******** "+ param);
Thread.Sleep (2000);
The catch (Interruptedexception e) {System.out.println ("interrupted");
return 1; else {throw new Exception ("Illegal argument!"
+param); }} public static class CalculaterunNable implements Runnable {private int param =-1;
public calculaterunnable (int param) {this.param = param;
@Override public void Run () {if (This.param = 0) {System.out.println ("param=" + param + "***over"); else if (This.param = 1) {//If flag value is 1, do an infinite loop try {while (true) {System.out.println ("looping**
"+ param);
Thread.Sleep (2000);
The catch (Interruptedexception e) {System.out.println ("interrupted");
} System.out.println ("param=" + param + "***over"); else {System.out.println ("illegal argument!")
+param);
}
}
}
}
Futuretask, an asynchronous computation that can be canceled. The result is obtained only when the calculation is complete, and the Get method is blocked if the calculation has not been completed .
Package com.example.test.callable;
Import java.util.concurrent.Callable;
Import java.util.concurrent.ExecutionException;
Import Java.util.concurrent.FutureTask;
public class Futuretasktest {/** * @param args */public static void main (string[] args) {testfuturetask (); private static void Testfuturetask () {Worker worker = new Worker ();//worker thread futuretask<integer> ft = new
Futuretask<integer> (worker);
New Thread (FT). Start ();
while (!ft.isdone ()) {try {System.out.println ("Monitor worker thread ...");
Thread.Sleep (500);
catch (Interruptedexception e) {e.printstacktrace ();
} try {int amount = Ft.get ();//return value SYSTEM.OUT.PRINTLN ("amount=" +amount);
catch (Interruptedexception e) {e.printstacktrace ();
catch (Executionexception e) {e.printstacktrace ();
} public static class Worker implements callable<integer> {private int flag = 100;
private int retVal = 0; @Override PublIC Integer Call () throws Exception {while (flag > 0) {System.out.println ("I ' m working ..." +flag);
flag--;
retval++;
Thread.Sleep (1000);
return retVal;
}
}
}