java 并行 CompletableFuture Future demo

Java

2018-01-09

39

0

技术:java8

运行环境:IDEA 15.2 + jdk8 + windows10

demo功能:提供java并行代码demo

源代码

package com.demoworld;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class Main {


    public static void main(String[] args) {
        futureDemo();
        
        serialDemo();
    }
    //并行计算
    private static void futureDemo() {
        DataHolder n1 = new DataHolder<>();
        CompletableFuture tmp1 = CompletableFuture.supplyAsync(() -> {
            int n = taskOne();
            n1.setData(n);
            return 1;
        });
        DataHolder n2 = new DataHolder<>();
        CompletableFuture tmp2 = CompletableFuture.supplyAsync(() -> {
            String n = taskTwo();
            n2.setData(n);
            return 2;
        });
        DataHolder n3 = new DataHolder<>();
        CompletableFuture tmp3 = CompletableFuture.supplyAsync(() -> {
            float n = taskThree();
            n3.setData(n);
            return 3;
        });
        CompletableFuture[] tmpArray = new CompletableFuture[3];
        tmpArray[0] = tmp1;
        tmpArray[1] = tmp2;
        tmpArray[2] = tmp3;

        long start = System.currentTimeMillis();
        CompletableFuture allOf = CompletableFuture.allOf(tmpArray);
        Object o = null;
        try {
            o = allOf.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println(String.format("1=%d, 2=%s, 3=%f", n1.getData(), n2.getData(), n3.getData()));
        System.out.println("并行耗时=" + (end - start));
    }

    private static void serialDemo() {
        long start = System.currentTimeMillis();
        taskThree();
        taskTwo();
        taskOne();
        long end = System.currentTimeMillis();

        System.out.println("串行耗时=" + (end - start));
    }
    //串行计算
    public static int taskOne() {
        long start = System.currentTimeMillis();
        for (long m = 0; m <= 999999999L; m++) {

        }
        long end = System.currentTimeMillis();
        System.out.println("task 1 =" + (end - start));
        return 1;
    }

    public static String taskTwo() {
        long start = System.currentTimeMillis();
        for (long m = 0; m <= 999999999L; m++) {

        }
        long end = System.currentTimeMillis();
        System.out.println("task 2 =" + (end - start));
        return "2";
    }

    public static float taskThree() {
        long start = System.currentTimeMillis();
        for (long m = 0; m <= 999999999L; m++) {

        }
        long end = System.currentTimeMillis();
        System.out.println("task 3 =" + (end - start));
        return 3.1f;
    }
}
 
 

欢迎添加微信,互相学习↑↑↑ -_-

发表评论

全部评论:0条

白老虎

programming is not only to solve problems, ways to think