[英]How to call the same method for two different objects in Java
I am writing a program that is intended to have two different Miners collect resources of a map and bring it back to a city they belong to. 我正在编写一个程序,旨在让两个不同的矿工收集地图资源并将其带回他们所属的城市。 This is the method describing their collection:
这是描述其集合的方法:
public void harvest(ArrayList<Resource> rez, SimpleWindow w) {
double min = Integer.MAX_VALUE;
int tracker = 0;
for (int i = 0; i < rez.size(); i++) {
if (Math.hypot(rez.get(i).getX() - this.x, rez.get(i).getY() - this.y) < min) {
min = Math.hypot(rez.get(i).getX() - this.x, rez.get(i).getY() - this.y);
tracker = i;
}
}
moveTo(rez.get(tracker).getX(), rez.get(tracker).getY(), w, rez);
this.value = this.value + rez.get(tracker).getValue();
SimpleWindow.delay(200);
rez.get(tracker).undraw(w);
rez.remove(tracker);
moveTo(city.getX(), city.getY(), w, rez);
city.addResource(this.value);
SimpleWindow.delay(200);
}
When I call this method for two different miners in an infinite while-loop like this (where r is an ArrayList of resource-objects and w my graphical window)... 当我在像这样的无限while循环中为两个不同的矿工调用此方法时(其中r是资源对象的ArrayList,而w是我的图形窗口)...
Miner robot = new Miner(500, 235, city1);
Miner robot1 = new Miner(850, 430, city2);
while (true){
robot.harvest(r, w);
robot1.harvest(r, w);
city1.draw(w);
}
...they simply take turns collecting resources instead of doing it at the same time. ...他们只是轮流收集资源,而不是同时进行。 I understand the reason for this but know of no way to solve the problem.
我了解原因,但无法解决问题。
I tried using separate threads like this... 我尝试使用像这样的单独线程...
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
while (true){
robot.harvest(r, w);
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
while (true){
robot1.harvest(r, w);
}
}
});
This worked to some degree as the miners mined at the same time, but it also produced a series of graphical glitches and problems with the ArrayList of the resource objects. 这在矿工同时进行开采的过程中起到了一定作用,但同时也产生了一系列图形故障和资源对象的ArrayList问题。 Is there a way to solve this problem?
有办法解决这个问题吗?
You should use a Collections.synchronizedList()
insead of your ArrayList. 您应该在ArrayList中使用
Collections.synchronizedList()
。
As for the graphical glitches, not really sure. 至于图形故障,不是很确定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.