一个需求需要三次访问数据库获取数据,然后把数据合并到一个map返回前端,如何使用线程池进行分别获取数据,主线程还能获取到线程池的请求的数据进行合并?
为什么需要用三个线程 不能再一个线程 查询3次么
package ConcurrentHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
// implementing Runnable interface
public class IterateAndModifyConcurrentHashMap implements Runnable {
// creating ConcurrentHashMap object of type <Integer, String>
static ConcurrentHashMap<Integer, String> chm = new ConcurrentHashMap<Integer, String>();
@Override
public void run() {
try {
// sleeping thread for 1000 ms
Thread.sleep(1000);
// removing entry with key=1
String value = chm.remove(1);
System.out.println("Entry with {key=1" + " & value=" + value + "} is removed");
} catch (InterruptedException iex) {
iex.printStackTrace();
}
System.out.println("Removal is done... !!");
}
/**
* main() method
*
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// adding key-value pairs to ConcurrentHashMap object
chm.put(1, "google.com");
chm.put(2, "youtube.com");
chm.put(3, "facebook.com");
// creating another thread
Thread newThread = new Thread(new IterateAndModifyConcurrentHashMap());
newThread.start();
// iterating CHM object using enhanced for-loop
for (Map.Entry<Integer, String> me : chm.entrySet()) {
System.out.println("{Key=" + me.getKey() + "\t" + "Value=" + me.getValue() + "}");
// sleeping thread for 2000 ms, after every turn
Thread.sleep(2000);
}
System.out.println("Iterating completed... !!");
}
}
CountDownLatch latch = new CountDownLatch(3);
ExecutorService executor = Executors.newFixedThreadPool(3);
List<Object> result = new ArrayList<>();
for(int i = 0; i < latch.getCount(); i ++){
executor.execute(new Runnable() {
@Override
public void run() {
// 查询sql; 注意需要在queryData结束时 增加代码: latch.countDown();
result.add(queryData());
}
});
}
try {
latch.await();
}catch (Exception e){
e.printStackTrace();
log.error("线程超时");
}
// 到这里,三个线程都执行完了
return result;
大概思路
使用ThreadGroup实现主线程等待所有子线程完成
public class ThreadGroupDemo {
public static void main(String[] args) {
System.out.println("main start");
ThreadGroup tg = new ThreadGroup("Parent ThreadGroup");
for (int j = 0; j < 10; j++) {
new Thread(tg, "t" + j) {
public void run() {
System.out.println("Thread: " + getName() + " running");
int small = 0;
int large = 10;
try {
Thread.sleep(1000 * (int) (Math.random() * (large - small + 1) + small));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
while (tg.activeCount() > 0) {
try {
System.out.println("Waiting for " + tg.activeCount() + " CThreads to Complete");
Thread.sleep(1000); // Main Thread or someThradObject.sleep();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("main end");
}
}
用CompletableFuture 线程调度来实现