java多线程的几种实现方式

举报
yd_245546638 发表于 2022/10/26 10:59:54 2022/10/26
【摘要】 java多线程的几种实现方式背景:从一个数组中,利用多个线程获取每个子元素的平方之后。 如数组为:{1,2,3,4} 。 则结果为: 1*1 + 2*2+3*3+4*4 = 30  1.普通实现。 遍历数组, 然后每个元素用一个线程进行处理。代码如下PlainBashC++C#CSSDiffHTML/XMLJavaJavascriptMarkdownPHPPythonRubySQLpubli...

java多线程的几种实现方式

背景:从一个数组中,利用多个线程获取每个子元素的平方之后。 如数组为:{1,2,3,4} 。 则结果为: 1*1 + 2*2+3*3+4*4 = 30  

1.普通实现。 遍历数组, 然后每个元素用一个线程进行处理。代码如下

PlainBashC++C#CSSDiffHTML/XMLJavaJavascriptMarkdownPHPPythonRubySQL
public static void main(String[] args) throws ExecutionException, InterruptedException {
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    List<Integer> list = Arrays.asList(1, 2, 3, 4);
    List<Future<Integer>> futures = new ArrayList<>();

    for (Integer integer : list) {
        Future<Integer> future = executorService.submit(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return integer * integer;
        });
        futures.add(future);
    }
    int sum = 0;
    // 收集结果
    for (Future<Integer> future : futures) {
        sum += future.get();
    }
    Thread.sleep(4000);
    System.out.println("MultipleThread.main");
    System.out.println(sum);
}

执行结果:

30

2.Completable异步获取结果

PlainBashC++C#CSSDiffHTML/XMLJavaJavascriptMarkdownPHPPythonRubySQL
public static void juc2() throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(3);
List<Integer> list = Arrays.asList(1, 2, 3, 4);
AtomicInteger sum = new AtomicInteger();
for (Integer integer : list) {
CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return integer * integer;

}, executorService).whenCompleteAsync((result, exception) -> {
sum.addAndGet(result);
});
}
executorService.shutdown();
Thread.sleep(1000);
System.out.println(sum);

}

3.java8Stream的实现方式

PlainBashC++C#CSSDiffHTML/XMLJavaJavascriptMarkdownPHPPythonRubySQL
public static void juc3() throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(4);
List<Integer> list = Arrays.asList(1, 2, 3, 4);

List<Integer> result = list.stream().map(key -> CompletableFuture.supplyAsync(() -> key * key, executorService)).map(CompletableFuture::join).collect(Collectors.toList());
int sum = 0;
for (Integer integer : result) {
sum += integer;
}
Thread.sleep(2000);
System.out.println(sum);
}

4.CountDownLatch的实现方式

PlainBashC++C#CSSDiffHTML/XMLJavaJavascriptMarkdownPHPPythonRubySQL
public static void juc4() {
ExecutorService executorService = Executors.newFixedThreadPool(4);
List<Integer> list = Arrays.asList(1, 2, 3, 4);
CountDownLatch countDownLatch = new CountDownLatch(list.size());
AtomicInteger sum = new AtomicInteger();
for (Integer integer : list) {
executorService.execute(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
sum.addAndGet(integer * integer);
countDownLatch.countDown();
});
}
executorService.shutdown();
try {
countDownLatch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("结果为:" + sum);
}


5.CompletableFuture.runAsync 的实现

PlainBashC++C#CSSDiffHTML/XMLJavaJavascriptMarkdownPHPPythonRubySQL
public static void juc5() {
ExecutorService executorService = Executors.newFixedThreadPool(4);
List<Integer> list = Arrays.asList(1, 2, 3, 4);
AtomicInteger sum = new AtomicInteger();
CompletableFuture.allOf(list.stream().map(key -> CompletableFuture.runAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
sum.addAndGet(key * key);

}, executorService)).toArray(CompletableFuture[]::new)).join();
executorService.shutdown();

System.out.println(sum);
}

6.

PlainBashC++C#CSSDiffHTML/XMLJavaJavascriptMarkdownPHPPythonRubySQL
public static void juc6() {
ExecutorService executorService = Executors.newFixedThreadPool(4);
List<Integer> list = Arrays.asList(1, 2, 3, 4);
CountDownLatch countDownLatch = new CountDownLatch(list.size());
AtomicInteger sum = new AtomicInteger();
for (Integer integer : list) {
executorService.execute(() -> {
sum.addAndGet(integer * integer);
countDownLatch.countDown();
});
}
executorService.shutdown();
try {
countDownLatch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(sum);
}

提供另一个思路, 定义执行次数(一个限制), 在runnable中进行自身处理之后, 检查限制, 完成时进行回调。

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。