Chapter 21 - Exercise 10

(4) Modify Exercise 5 following the example of the ThreadMethod class, so that runTask( ) takes an argument of the number of Fibonacci numbers to sum, and each time you call runTask( ) it returns the Future produced by the call to submit( ).




import java.util.concurrent.*;

public class Exercise10{
    //Executor
    private ExecutorService es=Executors.newCachedThreadPool();
    private Fibonacci f=new Fibonacci();
    //inner Callable
    public Future runTask(int num){
        return es.submit(new Callable<Integer>(){
            public Integer call(){
                Integer result=0;
                int index=0;
                while(++index<=num){
                    result+=f.fibo(index);
                }
                return result;
            }
        });
    }
    public void close(){es.shutdown();}

    public static void main(String[] args){
        Exercise10 ex=new Exercise10();
        Future f=ex.runTask(10);
        ex.close();
        try{
            System.out.println(f.get());
        }catch(InterruptedException ie){
            System.out.println(ie);
        }catch(ExecutionException ee){
            System.out.println(ee);
        }
    }
}



Need Java Developers? Hire Me »

I know Java. Talk is cheap, watch my code.

I live in CANADA now.