我有一个类,如下所示,具有三种方法
public class MyRunnable implements Runnable {
@Override
public void run() {
// what code need to write here
//to call the specific methods based on request types
}
public int add(int a, int b){
return a+b;
}
public int multiply(int a , int b){
return a*b;
}
public int division(int a , int b){
return a/b;
}
}
和我的主课一样
这里 r.multiply()、add() 和 Division() 方法将按顺序执行,但我想以多线程方式执行它们,因此我可以更快地得到结果。如何根据输入动态调用类的方法。如何传递给线程以及如何将结果从线程返回到调用线程。
public class ThreadDemo {
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
// how to do below calculation using multihtreading
// how to call a method and how to get result of a thread of same class
int result = r.multiply(1, 2) + r.add(4, 5) + r.division(10, 5);
System.out.println(result);
int newResult = r.add(20, 50);
System.out.println(newResult);
}
}
多线程会减慢该应用程序的速度(因为每个步骤的处理量太小,不足以证明跨线程分配工作的开销),应用程序可能在您察觉之前就已经完成了。
假设这是一个简化的例子,你可以写
MyRunnable r = new MyRunnable();
Executor exec = Executors.newFixedThreadPool(3);
CompletableFuture<Integer> mult = CompletableFuture.runAsync(() -> r.multiply(1, 2),exec );
CompletableFuture<Integer> add = CompletableFuture.runAsync(() -> r.add(4, 5) ,exec);
CompletableFuture<Integer> div = CompletableFuture.runAsync(() -> r.division(10, 5),exec);
CompletableFuture<Integer> result = mult.thenCombine(add, (multRes,addRes) -> multRes+addRest)
.thenCombine(div, (total,divRes) -> total+divRes);
int answer = result.join();
UPDATE为什么要使用显式定义的执行器?
它向读者展示how显式定义执行器(替代方案很简单)
-
通过将 Executor 定义为变量,您可以通过仅更改该变量分配来在 Common ForkJoinPool(或任何其他执行程序类型)之间切换(无需重构所有方法)。例如。
//ForkJoinPool common
Executor exec = ForkJoinPool.commonPool();
//Expanding thread pool
Executor exec = Executors.newCachedThreadPool();
//Just execute on the current thread
Executor exec = (Runnable r) -> r.run();
默认情况下,CompletableFuture.*Async 方法共享 Common ForkJoinPool,并行流以及没有特定执行器的 ForkJoinTasks 也是如此。除非团队的所有成员仔细考虑何时使用/不使用 Common ForkJoinPool,否则最终可能会意外地将异步 I/O 操作与同一个池中的 CPU 绑定处理混合在一起。
同样默认情况下,并行度设置为 Runtime.getRuntime().availableProcessors() - 1。同样,这可能适合也可能不适合当前的用例(对于某些用户来说,这可能意味着此示例是单线程的)。如果您需要更改默认值,可以通过系统属性“java.util.concurrent.ForkJoinPool.common.parallelism”进行配置。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)