Multithreading - Callable and Fibonacci Sequence Java

Topic details:

6-4 jmu-Java-07 multithreading-Callable and Fibonacci sequence (10 points)

Use Callable、Futureto solve the sum of the first n Fibonacci numbers in a multithreaded fashion.

topic content

Define CalculateTaska class that implements the Callableinterface
properties:private int n , which represents the Fibonacci sequence that requires n.
No-argument constructorpublic CalculateTask(int n) , assigning a value to property n.
Task function: Returns the Fibonacci value of n.

###main method description:

  1. nNumber of tasks to be created later.
  2. taskListA collection of tasks for calculating Fibonacci numbers.
  3. resultsThe result set returned after the task is completed.
  4. mainThe method finally uses the System.out.println("sum="+sum);output result

### Answers should include:

  1. The second half of the main method. Note that two should be included }, corresponding to the main method and the Main method respectively.{
  2. CalculateTaskclass definition

#### Referee Procedure Example

public class Main {

    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec = Executors.newCachedThreadPool();
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();//num of tasks
        List<CalculateTask> taskList = new ArrayList<CalculateTask>();
        List<Future<Integer>> results = new ArrayList<Future<Integer>>();
        int sum = 0;

        /*你的答案:*/

Answer code: 

        for(int i=1;i<=n;i++) 
        {
        	taskList.add(new CalculateTask(i));
        	results.add(exec.submit(new CalculateTask(i)));
        }
        exec.shutdown();
        for(Future<Integer> fi : results)
        {
        	try
        	{
        		sum=fi.get();
        	}
        	catch(Exception e)
        	{
        		e.printStackTrace();
        	}
        	
        }
        System.out.println("sum="+sum);
       
       
    }
}

class CalculateTask implements Callable<Integer>
{
	private int n;
	public CalculateTask(int n)
	{
		this.n=n;
	}
	@Override
	public Integer call()
	{
		int sum=1,fib1=0,fib2=1,fib3=1;
		for(int i=2;i<=n;i++)
		{
			fib3=fib1+fib2;
			fib1=fib2;
			fib2=fib3;
			sum+=fib3;
		} //求斐波那契数列前n项和
		return sum;
	}
	
}

Guess you like

Origin blog.csdn.net/qq_54587141/article/details/121213938