Joseph Tulowiecki wrote:Just trying to learn how threads operate here. My intention is to have these two threads run at the same time but it isn't happening. Only one is running. Does anyone know why?
Not sure what you mean by "only one is running." There are a couple of possible interpretations of that. However, here are some basics to be aware of.
1. You can never force multiple threads to be executing at the same time. Even if you have multiple cores or multiple CPUs, there's no guarantee that the JVM and OS will schedule the threads to run at the same time. All we can do by starting multiple concurrent threads is indicate that we are
allowing these various tasks to execute in parallel. The scheduling details are out of our hands.
2. If you do the following:
then t1 and t2 will be eligible to execute concurrently.
3. Despite the dire warnings in #1, if you do #2, then you will generally observe both threads running in parallel. In particular, if there is I/O involved, one thread will likely be swapped out while the it's waiting on I/O so the other can do whatever CPU-bound tasks it has, and then vice versa. If it's all CPU-bound but you have multiple cores or CPUs, then both will probably execute simultaneously, and if you have a single CPU/core, then they will take turns, and may do so fast enough that it looks like they're executing simultaneously. Note that these are generalities but in most common cases, that's the behavior you'll see.