mysql循环查到没数据库_【mysql】在for循环里使用多线程查询数据库
現在是需要在循環去查詢數據庫,然后進行數據匯總。大家有例子,建議參考意義嗎
回答
其實如果你是因為每個查詢任務都比較慢,所以想采用這種方式,不如去優化一下sql。或者你可以用下面的這種線程池的方式來處理,不過代碼的復雜度會大大提高的。
Futrue返回的包裝的數據類型對應你sql返回的類型
或者你可以使用fork/join來處理
public class CallableAndFuture {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newSingleThreadExecutor();
List> futures = new ArrayList<>();
for (int i = 10; i < 15; i++) {
futures.add(threadPool.submit(new Task(i)));
}
try {
Thread.sleep(1000);// 可能做一些事情
int allSum = 0;
for (Future f : futures) {
int fsum = f.get();
System.out.println("sum:" + fsum);
allSum += fsum;
}
System.out.println("allSum:" + allSum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
threadPool.shutdown();
}
}
class Task implements Callable {
private int i;
public Task(int i) {
this.i = i;
}
@Override
public Integer call() throws Exception {
// 替換成db的查詢
int sum = 0;
for (int j = 0; j <= i; j++) {
sum += j;
}
return sum;
}
}
總結
以上是生活随笔為你收集整理的mysql循环查到没数据库_【mysql】在for循环里使用多线程查询数据库的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 代码怎么优化_Mysql性能
- 下一篇: php并发访问mysql_php并发对M