java basis - to achieve Callable interface to create threads

Callable Package; 

/ * 
create a thread three ways: achieved Callable Interface 

1. Create a class implements Callable implementation 
2. The realization of the method call, this thread needs to perform operations declared in the secondary process 
3. Create Object Callable interface class 
4 . throw this object as a parameter FutureTask constructor, creates an object FutureTask 
5. FutureTask Thread object as the object constructor to create Thread objects, Start () 
6. the required if the return value of the method, use FutureTask. get () method to get 

understanding: 
    1.call () can return a value 
    2.call () can throw an exception, be caught out steps to obtain exception information 
    generics 3.Callable support 

@author zsben 
@Create 2020-01 14:31 -05 
* / 

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

class NumThread the implements a Callable { 

    @Override 
    public Object call() throws Exception {
        int sum=0;
        for(int i=2;i<=100;i+=2) {
            System.out.println(i);
            sum+=i;
        }
        return sum;//自动装箱了
    }
}


public class CallableTest {
    public static void main(String[] args) {
        NumThread numThread = new NumThread();

        FutureTask futureTask = new new FutureTask (numThread);
         new new the Thread (FutureTask) .start (); // FutureTask implements Runnable interface, starting the thread start Call () 

        the try {
             // GET () Returns the value is the constructor parameter FutureTask override implementation class Callable the call () returns the value of the 
            Object SUM = FutureTask. GET (); 
            the System. OUT .println (SUM); 
        } the catch (InterruptedException E) { 
            e.printStackTrace (); 
        } the catch (ExecutionException E) { 
            e.printStackTrace () ; 
        } 

    } 
}

Guess you like

Origin www.cnblogs.com/zsben991126/p/12153099.html