I still have some trouble wrapping my head around threads, and I’m trying to do this in the simplest way possible. I know that threads all have to have a run method they inherited from the Runnable class, but they can have additional methods as well, correct?
The reason being, I have a thread with some private variables and a run method. It calls it’s run function, and once it’s done, I want to reuse the thread with the exact same run method. It does exactly the same thing, just with different variables. So can I add something like a setArray method (the thread contains a private byte array) so I can just simply call run again with this new array, or is that not allowed. I guess to put it simply, it’d be something like
Thread thread = new MyThread();
thread.start();
// Check if the thread has finished in a non-blocking way
if (thread.isAlive() == false) {
thread.setArray(newArray)
thread.start();
}
Basically I only have a fixed number of threads and when the first thread is done running, I want to change the parameters a bit and have it run again. I don’t wan them to die, which seems to be what join does.
For the specific problem, I have say 4 threads, that each are give a set size block of a larger byte array. Each thread compresses that array with a Deflater and passes their result to a manager object that handles the synchronization. Once the first thread (as in the thread that got the first part of the array, not the first to finish) is done, it moves on to the next block not assigned to a thread.
I know thread pools are an option, but it seems a bit overkill plus I really don’t understand them (I’m still having trouble with just normal threads).
First, it is best to use the standard
Threadclass (don’t subclass it!) and put your application code into a class that implementsRunnable. This makes it much easier to separate your application logic from the problem of managing the threads.Second you have to understand that a Thread object calls the
runmethod just once. After therunmethod has returned (or terminated with an exception), the Thread object is dead, and cannot be brought back to life.So if you want to “reuse”
Threadinstances, you have to arrange that therunmethod is a loop that (somehow) waits for the next thing to be done. And before you know it you are implementing a thread pool.There is another (more “modern”) alternative to a thread pool. Create an
ExecutorServiceinstance, and use thesubmit()method to submit theRunnableinstances for execution. The interface javadoc has a good usage example, using an executor service instance with a private thread pool. If you wanted to, you could reuse theRunnableinstances, but generally it is simpler (and safer) to create new ones each time.