首页 > 编程语言 >Java8 多线程及并行计算demo

Java8 多线程及并行计算demo

时间:2022-08-30 15:23:38浏览次数:73  
标签:demo List System 并行计算 println new 多线程 public out

Java8 多线程及并行计算demo 

#接口
public interface RemoteLoader {
    String load();

    default void delay() {
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

#实现类
public class CustomerInfoService implements RemoteLoader{

    @Override
    public String load() {
        this.delay();
        return "基本信息";
    }
}

public class LabelService implements RemoteLoader{

    @Override
    public String load() {
        this.delay();
        return "学习标签";
    }
}

public class LearnRecordService implements RemoteLoader{

    @Override
    public String load() {
        this.delay();
        return "学习信息";
    }
}

public class WatchRecordService implements RemoteLoader{

    @Override
    public String load() {
        this.delay();
        return "观看服务";
    }
}

#测试类
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * 参考:https://blog.csdn.net/Alecor/article/details/113405297
 */
public class TestSync {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

//        sync();
//        testFuture();
//        testParallelStream();

//        testCompletableFuture();
//        testCompletableFuture2();
//        testCompletableFuture3();
        testCompletableFuture4();
    }

    /**
     * [基本信息, 学习信息]
     * 总共花费时间:2036
     */
    public static void sync(){
        long start = System.currentTimeMillis();
        List<RemoteLoader> remoteLoaderList = Arrays.asList(new CustomerInfoService(),new LearnRecordService());
        List<String> customerDetail = remoteLoaderList.stream().map(RemoteLoader::load).collect(Collectors.toList());
        System.out.println(customerDetail);
        long end = System.currentTimeMillis();
        System.out.println("总共花费时间:" + (end - start));
    }

    /**
     * [基本信息, 学习信息]
     * 总共花费时间:1037
     */
    public static void testFuture() {
        long start = System.currentTimeMillis();
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        List<RemoteLoader> remoteLoaders = Arrays.asList(new CustomerInfoService(), new LearnRecordService());

        List<Future<String>> futures = remoteLoaders.stream()
                .map(remoteLoader -> executorService.submit(remoteLoader::load))
                .collect(Collectors.toList());

        List<String> customerDetail = futures.stream()
                .map(future -> {
                    try {
                        return future.get();
                    } catch (InterruptedException | ExecutionException e) {
                        e.printStackTrace();
                    }
                    return null;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        System.out.println(customerDetail);
        long end = System.currentTimeMillis();
        System.out.println("总共花费时间:" + (end - start));
    }

    /**
     * [基本信息, 学习信息, 学习标签, 观看服务]
     * 总共花费时间:1081
     */
    public static void testParallelStream() {
        long start = System.currentTimeMillis();
        List<RemoteLoader> remoteLoaders = Arrays.asList(   new CustomerInfoService(),
                new LearnRecordService(),
                new LabelService(),
                new WatchRecordService());
        List<String> customerDetail = remoteLoaders.parallelStream().map(RemoteLoader::load).collect(Collectors.toList());
        System.out.println(customerDetail);
        long end = System.currentTimeMillis();
        System.out.println("总共花费时间:" + (end - start));
    }


    /**
     * doSomething...
     * Finish
     */
    public static void testCompletableFuture() {
        CompletableFuture<String> future = new CompletableFuture<>();
        new Thread(() -> {
            try {
                doSomething();
                future.complete("Finish");
            } catch (Exception e) {
                future.completeExceptionally(e);
            }          //任务执行完成后 设置返回的结果
        }).start();
        System.out.println(future.join());      //获取任务线程返回的结果
    }

    private static void doSomething() {
        System.out.println("doSomething...");
    }

    /**
     * doSomething...
     * Finish
     *
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static void testCompletableFuture2() throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            doSomething();
            return "Finish";
        });
        System.out.println(future.get());
    }

    /**
     * [基本信息, 学习信息, 学习标签, 观看服务]
     * 总共花费时间:1079
     *
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static void testCompletableFuture3() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        List<RemoteLoader> remoteLoaders = Arrays.asList(
                new CustomerInfoService(),
                new LearnRecordService(),
                new LabelService(),
                new WatchRecordService());
        List<CompletableFuture<String>> completableFutures = remoteLoaders
                .stream()
                .map(loader -> CompletableFuture.supplyAsync(loader::load).exceptionally(throwable -> "Throwable exception message:" + throwable.getMessage()))
                .collect(Collectors.toList());

        List<String> customerDetail = completableFutures
                .stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());

        System.out.println(customerDetail);
        long end = System.currentTimeMillis();
        System.out.println("总共花费时间:" + (end - start));
    }

    /**
     * [基本信息, 学习信息, 学习标签, 观看服务]
     * 总共花费时间:1051
     *
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static void testCompletableFuture4() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        List<RemoteLoader> remoteLoaders = Arrays.asList(
                new CustomerInfoService(),
                new LearnRecordService(),
                new LabelService(),
                new WatchRecordService());

        ExecutorService executorService = Executors.newFixedThreadPool(Math.min(remoteLoaders.size(), 50));

        List<CompletableFuture<String>> completableFutures = remoteLoaders
                .stream()
                .map(loader -> CompletableFuture.supplyAsync(loader::load, executorService))
                .collect(Collectors.toList());

        List<String> customerDetail = completableFutures
                .stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());

        System.out.println(customerDetail);
        long end = System.currentTimeMillis();
        System.out.println("总共花费时间:" + (end - start));
    }
}

 

标签:demo,List,System,并行计算,println,new,多线程,public,out
From: https://www.cnblogs.com/oktokeep/p/16639417.html

相关文章

  • 深度学习基础课: “判断性别”Demo需求分析和初步设计(下1)
    大家好~我开设了“深度学习基础班”的线上课程,带领同学从0开始学习全连接和卷积神经网络,进行数学推导,并且实现可以运行的Demo程序线上课程资料:本节课录像回放加QQ群,获得......
  • 多线程实战双色球
    随机数索引生成代码: usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceYpDotNet......
  • 2021年 西南石油大学超算与并行计算团队南充校区分队 第二届招新赛题解
      2021年SWPU(南充)超算团队招新赛总体难度并不是很大,大部分题目考察的是基本的编程能力,题目中涉及到了一些并行计算相关的名词和知识,选手在参加比赛的同时,既能够展示......
  • 一次有趣的多线程调度问题
    线程1----wait()1Objecto=newObject();2waitAndNotifyMap.put(urlId,o);3System.out.println(urlId+"运行到阻塞");4synchronized(o){5o.wait(1000);6......
  • C++【多线程编程】之【线程安全】
    1.线程安全是什么?在拥有共享数据的多条线程并行执行的程序中,线程安全的代码会通过同步机制保证各个线程都可以正常且正确的执行,不会出现数据污染等意外情况。2.什么情况......
  • C++【多线程编程】之【初识线程创建】
    1.线程创建函数调用pthread_create(句柄、参数、函数入口,函数入口的实参)intpthread_create(....)cppthread类:thread类的创建方法比较简便。但也有很多问题需要考虑......
  • 多线程
    原子性:一个操作或多个操作要么全部执行,且执行过程不会被任何因素打断,包括其他线程,要么全部不执行   每个线程都有自己独立的工作内存,从主内存中copy内容保存在工作......
  • java使用多种方式实现多线程及线程池的使用
    ​ 一、多线程实现了什么?为了解决负载均衡问题,充分利用CPU资源.为了提高CPU的使用率,采用多线程的方式去同时完成几件事情而不互相干扰.为了处理大量的IO操作时或处理......
  • java多线程2
    我们知道,线程有五种生命周期:新建,就绪,运行,阻塞,死亡.在我们编写,运行代码的过程中,可能出现线程死锁,线程阻塞等问题,下面介绍线程产生这些问题的原因,及解决的方案,......
  • python中的多线程与多进程
    线程概念:线程也叫轻量级进程,是操作系统能够进行运算调度的最小单位,它被包涵在进程之中,是进程中的实际运作单位。线程自己不拥有系统资源,只拥有一点儿在运行中必不可少的......