Java多线程求斐波那契数列的指定项

欧阳子遥 2019-11-15 09:32:47
在runThread(int num)函数中执行线程,创建Callable线程,Callable线程需要执行求第num项斐波那契数列的值,最后在runThread函数中获取Callable线程执行的结果,并打印输出。 package step2; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import java.util.*; public class Task { public void runThread(int num){ //请在此添加实现代码 /********** Begin **********/ // 在这里开启线程 获取线程执行的结果 ThreadCallable tc=new ThreadCallable(); FutureTask<Object> ft=new FutureTask<>(tc); Thread t1=new Thread(ft,"t1"); t1.start(); System.out.println("线程的返回值为:"+ft.get()); /********** End **********/ } } //请在此添加实现代码 /********** Begin **********/ /* 在这里实现Callable接口及方法 */ class ThreadCallable implements Callable<Integer>{ public Integer call() throws Exception{ int a=1;int b=1;int c=0; int num; public ThreadCallable(int num){ this.num=num; } if(num<=2){ c=1; } else{ for(int i=0;i<num;i++){ c=a+b; a=b; b=c; } } System.out.println(c); } } /********** End **********/ import java.util.Scanner; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import step2.ThreadCallable; public class Test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num = sc.nextInt(); ThreadCallable callable = new ThreadCallable(); if(!(callable instanceof Callable)){ System.out.println("未定义Callable线程,或者定义错误"); } Task task = new Task(); task.runThread(num); } } 错误 0/5src/step2/Task.java:34: error: illegal start of expression public ThreadCallable(int num){ ^ src/step2/Task.java:34: error: '.class' expected public ThreadCallable(int num){ ^ src/step2/Task.java:34: error: ';' expected public ThreadCallable(int num){ ^ 3 errors 好像一直是键盘输入的数据传入线程有错,还有task和threadcallable接口那里有问题
...全文
206 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
qybao 2019-11-15
  • 打赏
  • 举报
回复
这么明显的错误
class ThreadCallable implements Callable<Integer>{
public Integer call() throws Exception{
int a=1;int b=1;int c=0;
int num; //问题:这个是成员变量吧
public ThreadCallable(int num){ //问题:构造方法写在方法里了
this.num=num; //问题
} //问题

把上面问题3行移到call方法之前,也就是改成

class ThreadCallable implements Callable<Integer>{
int num;
public ThreadCallable(int num){
this.num=num;
}
public Integer call() throws Exception{
int a=1;int b=1;int c=0;

58,452

社区成员

发帖
与我相关
我的任务
社区描述
Java Eclipse
社区管理员
  • Eclipse
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧