Topic details:
6-4 jmu-Java-07 multithreading-Callable and Fibonacci sequence (10 points)
Use Callable、Future
to solve the sum of the first n Fibonacci numbers in a multithreaded fashion.
topic content
Define CalculateTask
a class that implements the Callable
interface
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:
n
Number of tasks to be created later.taskList
A collection of tasks for calculating Fibonacci numbers.results
The result set returned after the task is completed.main
The method finally uses theSystem.out.println("sum="+sum);
output result
### Answers should include:
- The second half of the main method. Note that two should be included
}
, corresponding to the main method and the Main method respectively.{
CalculateTask
class 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;
}
}