package projsamples;
import java.util.Collection;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class FactorialUsingThreads {
public static void main(String[] args) throws InterruptedException,ExecutionException{
Scanner reader = new Scanner(System.in);
int number = reader.nextInt();
ExecutorService es = Executors.newSingleThreadExecutor();
Future<Integer> result=es.submit(new FactorialCalc(number));
System.out.println("result value after calc is: "+ result);
int finalResult =(int)result.get();
System.out.println("The result of the factorial calculation for the"+number+"is: "+finalResult);
}
}
class FactorialCalc implements Callable<Integer>{
private int number;
public FactorialCalc(int number) {
super();
this.number = number;
}
@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
return factorial(number);
}
private Integer factorial(int number2) throws InterruptedException {
// TODO Auto-generated method stub
int number = number2;
int result = 1;
while(number2 !=0){
result = number*result;
number=number-1;
Thread.sleep(100);
}
System.out.println("result"+result);
return result;
}
}
在上面的代码中,我想做的是,我想找到用户输入的任何数字的阶乘编号。返回的结果是当我尝试输入整数对象并且获取值没有发生时的对象。我知道这可能是我无法做的非常基本的事情。
非常感谢所有可以提供帮助的人。
这与多线程有关。您只需要factorial
方法中的number2
,然后记住降低它。
private Integer factorial(int number2) throws InterruptedException {
int result = 1;
while(number2 != 0){
result = number2 * result;
number2 = number2 - 1;
Thread.sleep(100);
}
System.out.println("result"+result);
return result;
}