-2

So I have a superclass called Tile and many subclasses like BlueTile, GreenTile etc..

All instances of the different subclasses are stored in an ArrayList (eg. (blueTile1, blueTile2, greenTile1....)).

There is a method called "activateTile()" in the superclass, that all subclasses use in a different way.

Now when I loop trough the array and activate all blue Tiles with blueTile.activateTile() they will be activated one after another right?

How can I let all blueTiles in the Array call the method at the same time? Or is there a way to simply say "all instances of that class, do that method now"?

Thank you :)

Steffi
  • 1
  • Are you asking how to activate the tiles? Or they must be activated at the exact time? If you just want to activate the tiles, simply iterate the array list and call activeTile on each tile from the list. – Cheng Thao Feb 07 '22 at 15:34
  • I mean to activate them at the exact same time... – Steffi Feb 07 '22 at 17:17
  • @Seffi,go through this link once https://stackoverflow.com/help/how-to-ask – Anurag Sharma Feb 18 '22 at 07:02
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Feb 18 '22 at 07:02

1 Answers1

1

Unless you intend to launch a new Thread per instance, they will always being running methods sequentially.

Do you intend something like this?

void activateInParallel() {
    ArrayList<Thread> tileThreads = new ArrayList<>();
    for(Tile t : allTiles) {
        tileThreads .add(new Thread(()->t.activateTile()));
    }
    tileThreads.forEach(Thread::start);
}

I don't know enough details, but that is very likely not the best way to do it. I would consider using an Executor with a thread pool and offloading the work to it in a similar way.

    Executor executor = Executors.newFixedThreadPool(8);
    void activateInParallel() {
        for(Tile t : allTiles) {
            executor.execute(t::activateTile);
        }
    }
swpalmer
  • 3,890
  • 2
  • 23
  • 31