美文网首页
FutureTask例子(并行计算千万条数据并汇总)

FutureTask例子(并行计算千万条数据并汇总)

作者: TheUnforgiven | 来源:发表于2019-05-09 18:22 被阅读0次
/**
 * FutureTask
 * 将一千万条数据中的数字取出并相加
 */
public class FutureTaskTest {

    static List<String> list = new ArrayList<>(10000000);

    public static void main(String[] args) throws Exception {
        
        //1.生成一千万条数据
        for (int i = 0, j = 10000000; i < j; i++) {
            list.add("AAAA" + 2 + "ssss");
        }
        System.out.println("list set success");

        //2.普通循环测试
        long start = new Date().getTime();
        long resultSum = 0;
        for (int i = 0, j = 10000000; i < j; i++) {
            String s = list.get(i);
            String b = Pattern.compile("[^0-9]").matcher(s).replaceAll("");
            Integer integer = Integer.valueOf(b);
            resultSum += integer;

        }
        long end = new Date().getTime();
        System.out.println((end - start) + "," + resultSum);

        //3.futureTask测试
        long start2 = new Date().getTime();

        FutureTask<Long> futureTask1 = new ChildTask(0, 3333333).getFutureTask();
        FutureTask<Long> futureTask2 = new ChildTask(3333333 + 1, 3333333 * 2).getFutureTask();
        FutureTask<Long> futureTask3 = new ChildTask(3333333 * 2 + 1, 10000000 - 1).getFutureTask();

        Long result = futureTask1.get();//获取结果,此时如果task未结束,会阻塞
        Long result2 = futureTask2.get();
        Long result3 = futureTask3.get();

        long end2 = new Date().getTime();

        System.out.println((end2 - start2) + "," + (result + result2 + result3));


    }

}
//子线程
class ChildTask {

    int start;
    int end;

    public ChildTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    public FutureTask<Long> getFutureTask() {
        Callable<Long> callable = () -> {
            Long result = 0L;
            for (int i = start, j = end; i <= j; i++) {
                String s = FutureTaskTest.list.get(i);
                String b = Pattern.compile("[^0-9]").matcher(s).replaceAll("");
                Integer num = Integer.valueOf(b);
                result += num;

            }
            return result;
        };
        FutureTask<Long> task = new FutureTask<>(callable);
        new Thread(task).start();
        return task;
    }
}

结果:比普通循环快3s


image.png

相关文章

网友评论

      本文标题:FutureTask例子(并行计算千万条数据并汇总)

      本文链接:https://www.haomeiwen.com/subject/yiegoqtx.html