user985673
user985673

Reputation: 25

How to loop threads

I know in java you can create an array or list(honestly I forget which one) that you can store a series of classes. I want to be able to have a program that has one of those lists and will loop through each class and run a certain method in each class(yes all the classes extend one abstract class) in a new thread. Is this possible? I am very sorry if I am not describing my problem well if some people comment and say I need to describe it better I will attempt to.

Upvotes: 0

Views: 113

Answers (2)

Chris Nava
Chris Nava

Reputation: 6802

Use a ThreadPoolExeuctor and feed it a BlockingQueue< Runable>.

Upvotes: 0

Alnitak
Alnitak

Reputation: 340045

(tweaking StriplingWarrior's example class names here to show how to thread it)

To run in a thread your classes need to implement Runnable, i.e. contain the method public void run(), thus:

public abstract class Foo implements Runnable {
    public void run() {
       bar();
    }
    public void bar();  // the method that'll be overridden
}

Then, for each element in your list:

List<Foo> foos;
for (Foo foo : foos) {
    new Thread(foo).start();
}

Upvotes: 2

Related Questions