Mr.Potson
Mr.Potson

Reputation: 59

Storing multiple Threads in Java

Suppose I have a class which implements Runnable interface, and I am to make 5 instances of given class in the main program. I would like to store them either in array, or a collection. Since the class implements Runnable it is my understanding that the only way I can store it is in a thread container such as Thread[]. However if I do this I can't use classes overridden toString() method for example, or any other custom method/field.

public class LittleClass implements Runnable{
    public void run(){

    }
}

public static void main(String[] args){
    Thread[] smallClasses = new Thread[5];

    // initialize and so...

    smallClasses[i].customField//not accessible
    System.out.println(smallClasses[i])//gives Thread[Thread-X,X,]
}

Upvotes: 0

Views: 666

Answers (2)

Gray
Gray

Reputation: 116908

You should consider using an ExecutorService. Then you keep an array of your job classes and submit them to the service to be run.

// create a thread pool with as many workers as needed
ExecutorService threadPool = Executors.newCachedThreadPool();
// submit your jobs which should implements Runnable
for (YourRunnable job : jobs) {
    threadPool.submit(job);
}

Once you have submitting your jobs, you shut down the service, wait for it to finish, and then you can interrogate your jobs to get information from them.

// shuts the pool down but the submitted jobs still run
threadPool.shutdown();
// wait for all of the jobs to finish
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
// now go back and print out your jobs
for (YourRunnable job : jobs) {
    System.out.println(jobs.toString());
}

Here's a good tutorial on the subject.

Upvotes: 2

CodeGuy
CodeGuy

Reputation: 28905

You can create your custom class which implements Runnable and then story an array of those custom classes.

So, for instance, in the code you wrote above, you can always use

LittleClass[] objs = new LittleClass[4];
for(int i = 0; i < objs.length; i++) {
   objs[i] = new LittleClass();
}

Upvotes: 0

Related Questions