我需要一些帮助在多线程环境(java 8)中并行运行进程,以便更快地处理进程。这是我的用例。
- 从数据库中检索记录(大量,数百万条记录)例如:从EMP中选择*,其中…..和MOD(PK,totalLoops -1)=当前循环限制10,000(尚未决定限制)– PostgreSQL数据库
- 与云平台建立连接,读取JSON,然后将数据库中的数据验证为JSON密钥,然后返回是否经过验证的
- 使用上面每个检索到的记录的验证状态来更新数据库。
从数据库中检索记录集并并行运行过程的想法是使用MOD值,并且线程ID将被替换为“?” 在查询中。 Ex MOD(id,ThreadID)=线程-1
Q1。问题是,我无法将线程ID作为参数传递给Runnable或Callable。 Q2。我是否还可以使用stream和forEach来调用ArrayList-process.getGcpdataFromJSON();我可以重载此方法。 是否可以在一个线程中有一个线程并进行流传输并有多个线程?
private int totalNumberOfThreads = 10;
Callable<String> callabletask = () -> {
TimeUnit.MILLISECONDS.sleep(1000);
System.out.println("Current time :: " + LocalDateTime.now());
for (int i=0; i<10; i++{
process.getGcpdataFromJSON(ArrayList queryDataList =
Dataaccess.getInstance().getDataToProcess(i,totalNumberOfThreads));
}
return “Done”
};
//Executor service instance
ExecutorService executor = Executors.newFixedThreadPool(2);
//2. execute individual tasks using submit() method
Set<Callable<String>> callables = new HashSet<Callable<String>>();
for (int i =0; i<10; i++){
executor.submit(callabletask);
callables.add(new Callable<String>() {
@Override
public String call() throws Exception {
return "Task Done:";
}
});
}
String result = executor.invokeAny(callables);
System.out.println("result = " + result);
//Shut down the executor service
executor.shutdownNow();