Let all instances of object call method at same time (java)

67
June 27, 2022, at 08:00 AM

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

Answer 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);
        }
    }
Rent Charter Buses Company
READ ALSO
change the time interval in spring app using the code

change the time interval in spring app using the code

I have a spring boot applicate that is using many types of date objects it like:

37
How to move table row to the top within a loop - React

How to move table row to the top within a loop - React

I have a loop which goes through an array (files) of objects (person)If the person works as a doctor or a vet I would like to display their row at the top of the table, if not, they should be displayed under the doctors and vets

32
Can we create an object in Java with out class like in js or python with random key and values

Can we create an object in Java with out class like in js or python with random key and values

Like in other programing languages - python or JS, when we create a rest api specifically post for the request body we attract some JSON Object

33
Jenkins pipeline library build using Java instead of Groovy

Jenkins pipeline library build using Java instead of Groovy

I would like to write my company Jenkins Pipeline Library using Java not Groovy, as groovy is slower than JavaI tried to find examples of such Java Jenkins library source code, but I found only Groovy

54