我有一个bean
,它会在页面上显示大量信息。通过点击db
获得此信息的每一位,目前这是按顺序发生的。以下是我bean
的一些示例代码:
int transactionCount = dao.getTransactionCount();
int personCount = dao.getPersonCount();
int carCount = dao.getCarCount();
int houseCount = dao.getHouseCount();
我正在运行Java 7
。我怎么能并行运行呢?我查看了ExecutorService
和ForkJoin
,但两者似乎都要一遍又一遍地运行相同的代码。那不是我在这里做的。加快这一过程的最佳方法是什么?
答案 0 :(得分:1)
当然,您可以向单个执行程序提交不同的任务。 您只需将期货分开以获得每项任务的结果:
static ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
//start threads
Future<Integer> transactionCountFuture = executor.submit(()-> dao.getTransactionCount());
Future<Integer> personCountFuture = executor.submit(()-> dao.getPersonCount());
Future<Integer> carCountFuture = executor.submit(()-> dao.getCarCount());
Future<Integer> houseCountFuture = executor.submit(()-> dao.getHouseCount());
//wait until all calls returns a result
int transactionCount = transactionCountFuture.get();
int personCount = personCountFuture.get();
int carCountCount = carCountFuture.get();
int houseCount = houseCountFuture.get();