用Java实现,要求创建一个集合,创建3个子线程,往该集合中添加随机1到10000的整数,当集合中数据达到100个的时候停止添加,如果数字重复抛出异常提示用户
时间: 2024-01-22 12:03:26 浏览: 18
好的,下面是使用Java实现的代码:
```java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
Set<Integer> set = new HashSet<>();
Thread thread1 = new Thread(() -> {
while (list.size() < 100) {
int num = new Random().nextInt(10000) + 1;
if (set.contains(num)) {
throw new RuntimeException("Duplicate number found: " + num);
}
set.add(num);
list.add(num);
System.out.println("Thread 1 added: " + num);
}
});
Thread thread2 = new Thread(() -> {
while (list.size() < 100) {
int num = new Random().nextInt(10000) + 1;
if (set.contains(num)) {
throw new RuntimeException("Duplicate number found: " + num);
}
set.add(num);
list.add(num);
System.out.println("Thread 2 added: " + num);
}
});
Thread thread3 = new Thread(() -> {
while (list.size() < 100) {
int num = new Random().nextInt(10000) + 1;
if (set.contains(num)) {
throw new RuntimeException("Duplicate number found: " + num);
}
set.add(num);
list.add(num);
System.out.println("Thread 3 added: " + num);
}
});
thread1.start();
thread2.start();
thread3.start();
try {
thread1.join();
thread2.join();
thread3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Result: " + list);
}
}
```
这段代码会创建一个集合`list`和一个集合`set`,然后创建3个子线程,每个线程会循环添加随机1到10000的整数到`list`中,同时使用`set`来检查是否有重复的数字,如果有则抛出异常。当`list`的大小达到100时,线程会停止添加数字。最后,使用`join()`方法等待所有线程执行完毕,并输出`list`中的结果。