我有一个如下的类,有三个方法
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;
}
}
和我的主要类为blow在这里,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为什么使用显式定义的执行器?
它向读者如何显式定义执行器(另一种选择很简单)
通过将Executor定义为变量,您可以通过更改该变量赋值(您不必重构所有方法)在Common ForkJoinPool(或任何其他Executor类型)之间切换。例如
//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。*异步方法共享公共ForkJoinPool,并行流也是如此,以及没有特定执行器的forkjointask。除非团队的所有成员都仔细考虑何时使用/不使用Common ForkJoinPool,否则您可能会意外地将异步I/O操作与CPU绑定处理混合在同一个池中。
默认情况下,并行度设置为Runtime.getRuntime(). availableprocessors() - 1。同样,这可能适合也可能不适合手头的用例(对于某些用户来说,这可能意味着这个示例是单线程的)。如果您需要更改默认值,可以通过系统属性"java.util.concurrent.ForkJoinPool.common.parallelism"进行配置。