package com;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TestThread {
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
int all = test1();
long end = System.currentTimeMillis();
System.out.println("all的值为:" + all);
System.out.println("耗时秒:" + (end - start) / 1000);
long start2 = System.currentTimeMillis();
int all2 = test2();
long end2 = System.currentTimeMillis();
System.out.println("all2的值为:" + all2);
System.out.println("2耗时秒:" + (end2 - start2) / 1000);
}
/**
* 不用多线程的方法测试
*
* @return
* @throws InterruptedException
*/
private static int test1() throws InterruptedException {
int all = 0;
for (int i = 0; i < 20; i++) {
//这里模拟业务和耗时操作
Thread.sleep(500);
all = all + i;
}
return all;
}
/**
* 用了多线程的方法测试
*
* @return
* @throws InterruptedException
* @throws InterruptedException
* @throws ExecutionException
*/
private static int test2() throws InterruptedException, InterruptedException, ExecutionException {
ExecutorService service = Executors.newFixedThreadPool(10);
ArrayList<Future<Integer>> list = new ArrayList<>();
for (int i = 0; i < 20; i++) {
CallableTest callableTest = new CallableTest(i);
list.add(service.submit(callableTest));
}
int all = 0;
for (Future<Integer> dateFuture : list) {
all = all + dateFuture.get();
}
return all;
}
}
package com;
import java.util.concurrent.Callable;
public class CallableTest implements Callable {
int i;
CallableTest(int sort){
i=sort;
}
@Override
public Object call() throws Exception {
//这里模拟业务和耗时操作
Thread.sleep(500);
return i;
}
}
运行结果:结果都获取到了,且一样;多线程优化完后只要1秒,不用多线程要10秒