java多线程查询list
时间: 2023-11-27 11:03:55 浏览: 39
以下是Java多线程查询List的示例代码:
```java
import java.util.ArrayList;import java.util.List;
import java.util.concurrent.*;
public class MultiThreadListSearch {
public static void main(String[] args) throws InterruptedException, ExecutionException {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 100000; i++) {
list.add(i);
}
ExecutorService executorService = Executors.newFixedThreadPool(10);
List<Future<Integer>> futures = new ArrayList<>();
for (int i = 0; i < 10; i++) {
int start = i * 10000;
int end = (i + 1) * 10000;
Future<Integer> future = executorService.submit(new SearchTask(list, start, end, 5000));
futures.add(future);
}
int result = 0;
for (Future<Integer> future : futures) {
result += future.get();
}
System.out.println("Result: " + result);
executorService.shutdown();
}
static class SearchTask implements Callable<Integer> {
private List<Integer> list;
private int start;
private int end;
private int target;
public SearchTask(List<Integer> list, int start, int end, int target) {
this.list = list;
this.start = start;
this.end = end;
this.target = target;
}
@Override
public Integer call() throws Exception {
int count = 0;
for (int i = start; i < end; i++) {
if (list.get(i) == target) {
count++;
}
}
return count;
}
}
}
```
上述代码中,我们首先创建了一个包含100000个整数的List,然后创建了一个包含10个线程的线程池。接着,我们将List分成10个部分,每个线程负责查询其中一个部分。每个线程查询完成后,将查询结果返回给主线程,主线程将所有结果相加得到最终结果。这样,我们就实现了多线程查询List的功能。