Multithreading --Callable Interface

pers.aaa.callable Package; 

Import java.util.concurrent.Callable; 

public  class MyCallable the implements a Callable <Integer> { 

    public Integer Call () throws Exception { // Call method may throw an exception, run not 
            int SUM = 0 ;
             for ( int I = 0 ; I <= 100 ; I ++ ) 
                SUM = SUM + I;
             return SUM; // Call method returns a value 
        
    } 

}
package pers.aaa.callable;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Test {
public static void main(String[] args) throws InterruptedException, ExecutionException {
     MyCallable mc=new MyCallable();
     FutureTask<Integer> result =  new FutureTask<Integer>(mc);//创建一个 FutureTask,一旦运行就执行给定的 Callable
     new Thread(result).start();
     Integer sum = result.get();  
     System.out.println(sum);
}
}

 

Guess you like

Origin www.cnblogs.com/zhai1997/p/11370414.html