Java一个用户集合,如何把集合交给10个异步线程去执行
时间: 2024-02-02 10:04:59 浏览: 119
好的,以下是一个简单的用户集合,并且附上将集合交给10个异步线程执行的代码示例:
```java
public class UserCollection {
private List<User> users;
public UserCollection(List<User> users) {
this.users = users;
}
public List<User> getUsers() {
return users;
}
}
```
```java
public class UserProcessor {
private ExecutorService executorService;
private final int THREAD_COUNT = 10;
public UserProcessor() {
executorService = Executors.newFixedThreadPool(THREAD_COUNT);
}
public void processUsers(UserCollection userCollection, UserProcessorCallback callback) {
List<User> users = userCollection.getUsers();
int userCount = users.size();
int batchSize = userCount / THREAD_COUNT;
int remaining = userCount % THREAD_COUNT;
int start = 0, end = 0;
for (int i = 0; i < THREAD_COUNT; i++) {
start = end;
end += batchSize;
if (i < remaining) {
end++;
}
List<User> batch = users.subList(start, end);
executorService.submit(() -> {
for (User user : batch) {
// 模拟处理用户的逻辑
System.out.println("正在处理用户 " + user.getName());
callback.onUserProcessed(user);
}
});
}
}
public void shutdown() {
executorService.shutdown();
}
}
```
```java
public interface UserProcessorCallback {
void onUserProcessed(User user);
}
```
使用示例:
```java
public class Test {
public static void main(String[] args) {
List<User> users = Arrays.asList(
new User("张三", "zhangsan@demo.com"),
new User("李四", "lisi@demo.com"),
new User("王五", "wangwu@demo.com"),
new User("赵六", "zhaoliu@demo.com"),
new User("钱七", "qianqi@demo.com"),
new User("孙八", "sunba@demo.com"),
new User("周九", "zhoujiu@demo.com"),
new User("吴十", "wushi@demo.com")
);
UserCollection userCollection = new UserCollection(users);
UserProcessor userProcessor = new UserProcessor();
userProcessor.processUsers(userCollection, user -> {
// 在这里处理每个用户处理完成的逻辑
System.out.println("用户 " + user.getName() + " 处理完成");
});
userProcessor.shutdown();
}
}
```
在这个示例中,我们首先创建了一个包含多个用户的用户集合,然后将其交给`UserProcessor`对象处理。在处理用户集合时,我们将用户集合分成了10个批次,每个批次由一个异步线程处理。当一个异步线程处理完一个批次的用户后,会调用`UserProcessorCallback`对象的`onUserProcessed`方法,我们可以在这个方法里处理每个用户处理完成的逻辑。
需要注意的是,在使用线程池时,我们必须在程序结束时调用`shutdown`方法来关闭线程池。
阅读全文