java问题 有一个list有1W条数据, 现在我想用多线程不重复的读取list中的数据,要怎么写? 30
例如:线程N读list[0]线程N读list[1]线程N读list[2]...线程N读list[9999]线程N读list[10000]...
例如:
线程N读list[0]
线程N读list[1]
线程N读list[2]
...
线程N读list[9999]
线程N读list[10000] 展开
线程N读list[0]
线程N读list[1]
线程N读list[2]
...
线程N读list[9999]
线程N读list[10000] 展开
2个回答
展开全部
@Slf4j
public class FixedThreadPool {
/** 请求总数**/
private static int clientTotal = 100;
public static AtomicInteger atomicInteger = new AtomicInteger(0);
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(10);
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
for (int i = 0; i < clientTotal; i++) { //这里clientTotal你换成你的list的size
atomicInteger.incrementAndGet();
while (atomicInteger.get() > 4){
Thread.sleep(10);
}
executorService.execute(() -> {
consoleLog();
countDownLatch.countDown();
atomicInteger.decrementAndGet();
});
}
countDownLatch.await();
executorService.shutdown();
log.info("全部执行完毕");
}
private static void consoleLog(){
try {
log.info("hello");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class FixedThreadPool {
/** 请求总数**/
private static int clientTotal = 100;
public static AtomicInteger atomicInteger = new AtomicInteger(0);
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(10);
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
for (int i = 0; i < clientTotal; i++) { //这里clientTotal你换成你的list的size
atomicInteger.incrementAndGet();
while (atomicInteger.get() > 4){
Thread.sleep(10);
}
executorService.execute(() -> {
consoleLog();
countDownLatch.countDown();
atomicInteger.decrementAndGet();
});
}
countDownLatch.await();
executorService.shutdown();
log.info("全部执行完毕");
}
private static void consoleLog(){
try {
log.info("hello");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
2015-06-05
展开全部
把读取的方法写成同步方法。然后起很多线程调用这个读的方法去读该list。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询