Java, create threads Three ways: to achieve Callable Interface



java.util.concurrent.Callable Import;
Import java.util.concurrent.ExecutionException;
Import java.util.concurrent.FutureTask;

/ **
* Create a thread Three ways: implement Callable interface. --- JDK 5.0 added
*
*
* How to understand the way to achieve Callable interface to create multi-threaded multi-threaded Runnable interface to create powerful than achieved?
* 1. call () can return a value.
* 2. call () can throw an exception, being outside of the capture operation, access to information abnormalities
* 3. Callable supports generic
*
* /
// 1. Create an implementation class that implements the Callable
class NumThread the implements Callable {
/ . / 2 to achieve a method call, this operation is declared to be executed thread () in the call
@Override
public Object call () throws Exception {
int SUM = 0;
for (int I =. 1; I <= 100; I ++) {
if (i% 2 == 0) {
System.out.println (I);
SUM = I +;
}
}
return SUM;
}
}


public class ThreadNew {
public static void main (String [] args) {
.. 3 // Create Callable interface class object
NumThread numThread = numThread new new ();
// this. 4 Callable object class interface as FutureTask passed to the constructor, creates FutureTask object.
FutureTask FutureTask = new new FutureTask (numThread);
.. 5 // FutureTask the object passed as an argument to the Thread class constructor Create Thread object and calls Start ()
new new Thread (FutureTask) .start ();

the try {
. Callable acquired. 6 // the return value of the call
// get () returns the value is the FutureTask Callable implementation class constructor argument rewritten to call () return value.
Object sum = futureTask.get();
System.out.println("总和为:" + sum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}

}

Guess you like

Origin www.cnblogs.com/wpy188/p/12099902.html