现在有一个的箱子里面是一些随机整数 有三个人从箱子中取出数据java通过实现runnable接口 创建3个线程模拟从箱子中抽取数据的操作
时间: 2024-02-05 16:11:46 浏览: 73
好的,下面是一个简单的Java代码实现:
```java
import java.util.ArrayList;
import java.util.Random;
public class Box {
private ArrayList<Integer> numbers;
public Box(int numCount) {
numbers = new ArrayList<Integer>();
Random rand = new Random();
for (int i = 0; i < numCount; i++) {
numbers.add(rand.nextInt(100));
}
}
public synchronized int getNumber() {
if (numbers.size() == 0) {
return -1;
}
int index = new Random().nextInt(numbers.size());
int number = numbers.get(index);
numbers.remove(index);
return number;
}
}
class Person implements Runnable {
private String name;
private Box box;
public Person(String name, Box box) {
this.name = name;
this.box = box;
}
public void run() {
while (true) {
int number = box.getNumber();
if (number == -1) {
System.out.println("Box is empty, " + name + " stops getting numbers.");
break;
}
System.out.println(name + " gets " + number + " from the box.");
try {
Thread.sleep(new Random().nextInt(5000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
Box box = new Box(10);
Thread t1 = new Thread(new Person("Person1", box));
Thread t2 = new Thread(new Person("Person2", box));
Thread t3 = new Thread(new Person("Person3", box));
t1.start();
t2.start();
t3.start();
}
}
```
以上代码中,Box类表示一个箱子,包含从中取出的随机整数列表。Person类表示一个人,通过不断调用Box类的getNumber方法从箱子中取出一个随机整数,并做一些处理。Main类启动三个线程分别代表三个人进行操作。由于多线程环境下Box类的getNumber方法可能会被多个线程同时调用,为了避免出现并发问题,这里使用了synchronized关键字对该方法进行了同步处理。
阅读全文