我们知道100的阶乘的值为:
100的阶乘为:93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
这个值很大,一般数据类型无法接受,只有用JAVA程序语言中的 BigInteger 来接收
采用并发框架 executor 来计算
?
程序源代码
package text.ght02;
//编写一个测试程序,利用 executor 并发框架,实现 100!分解为 10 个子任务运算。
public class Main {
public static void main(String[] args) throws InterruptedException {
// 创建一个执行服务器
Server server=new Server();
// 创建10个任务,并发给执行器,等待完成
for (int i=0; i<10; i++){
Task task=new Task("Task "+i);
Thread.sleep(10);
server.submitTask(task);
}
server.endServer();
}
}
package text.ght02;
import text.ght02.Task;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 执行服务器
*
*/
public class Server {
//线程池
private ThreadPoolExecutor executor;
public Server(){
executor=(ThreadPoolExecutor)Executors.newCachedThreadPool();
//executor=(ThreadPoolExecutor)Executors.newFixedThreadPool(5);
}
//向线程池提交任务
public void submitTask(Task task){
System.out.printf("Server: A new task has arrived\n");
executor.execute(task); //执行 无返回值
System.out.printf("Server: Pool Size: %d\n",executor.getPoolSize());
System.out.printf("Server: Active Count: %d\n",executor.getActiveCount());
System.out.printf("Server: Completed Tasks: %d\n",executor.getCompletedTaskCount());
}
public void endServer() {
executor.shutdown();
}
}
package text.ght02;
import javax.management.StringValueExp;
import java.math.BigInteger;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* Task 任务类
*/
public class Task implements Runnable {
private String name;
public volatile BigInteger result = new BigInteger("1");//结果
public volatile int time = 1;//用于计算100的阶乘,当做工具数
public Task(String name) {
this.name = name;
}
public void run() {
while (true)// 循环是指线程不停的去执行业务操作
{
String str = Thread.currentThread().getName();
BigInteger num = new BigInteger(String.valueOf(time));
result = result.multiply(num);
time++;
System.out.println(str + "得到的值为:" + result);
System.out.printf("%s: Task %s: Finished on: %s\n", Thread.currentThread().getName(), name, new Date());
// for (int i = k; i < k + 10; i++) {
// BigInteger num = new BigInteger(String.valueOf(i));
// result = result.multiply(num);
// System.out.printf("%s: Task %s: Finished on: %s\n", Thread.currentThread().getName(), name, new Date());
// }
if (time > 100) {
System.out.println("最终结果为:" + result);
break;
}
}
}
}
?
|