Reputation: 5568
I'm writing a simple program that calculates two squared matrix multiplication. The program should divide the work between the number of threads I predefine.
The way I do it is that each thread calculates different lines of the resulting matrix.
So the run() method each thread executes is:
@Override
public void run() {
for (int y = 0; y < numLines; y++)
for (int x = 0; x < matrixSize; x++)
result[startLine + y][x] = singleIndexCalc(startLine + y, x);
}
This program has no synchronization (anywhere). So my question is if I have to take care of joining the threads before ending the main() method or it does not matter as the threads will (for sure) finish running and die.
I'm asking this as I don't want to leave running threads (something that might happen when they get stuck waiting for instance), but in this example it's just not possible.
Thank you!
Upvotes: 3
Views: 389
Reputation: 17556
Yes, the main thread can end running before other threads end.
Look at the setDaemon()
method of the Thread
class: https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#setDaemon(boolean)
Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.
This method must be invoked before the thread is started.
The JVM will shut down after all non-daemon threads are finished executing.
In your case, once the main thread, and the worker threads are finished executing, the JVM will shut down, and program will end.
An interesting note: if the main thread doesn't call join()
on any of the worker threads, it could actually end before the worker threads finish executing.
Upvotes: 1