java多线程的几种实现方式
【摘要】 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)