简体   繁体   中英

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)...

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. Is there a way to solve this problem?

You should use a Collections.synchronizedList() insead of your ArrayList.

As for the graphical glitches, not really sure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM