创建多线程的方式三:实现Callable接口。
package com.day0207_3;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
class NumThread implements Callable{
@Override
public Object call() throws Exception {
int sum=0;
for (int i = 1; i <=100 ; i++) {
if(i%2==0){
System.out.println(i);
sum+=i;
}
}
return sum;
}
}
public class ThreadNew {
public static void main(String[] args) {
NumThread numThread=new NumThread();
FutureTask futuretask = new FutureTask(numThread);
new Thread(futuretask).start();
try {
Object sum = futuretask.get();
System.out.println("总和为"+sum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
版权声明:本文内容来自第三方投稿或授权转载,原文地址:https://jsss-1.blog.csdn.net/article/details/113745164,作者:日星月云,版权归原作者所有。本网站转在其作品的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如因作品内容、版权等问题需要同本网站联系,请发邮件至ctyunbbs@chinatelecom.cn沟通。