I have multiple threads printing data. All the data does print; however, they are not in order. Meaning Thread 2 starts printing while Thread 1 is not done yet, which causes inconsistency. How do I guarantee consistency ? Meaning Thread 2 can print once Thread 1 is done.
I have multiple threads printing data. All the data does print; however, they are
Share
From your comments, you are looking to achieve
1 1 1 1 2 2 2 2so what you’d need to do is actually wait for Thread1 to complete, then start Thread2, like this:however, if you want to have both threads start, but have Thread2 wait part way through its processing, while waiting for Thread1 to complete – this can be done with a few techniques – one in particular comes to mind – using
Semaphore.Example:
Ok, firstly define your thread constructors to accept a Semaphore, thus:
Thread1’s run method would look like this:
Thread2’s run method would look something akin to this:
Now, setting up the threads would be done like this: