How it works...

We have modified the code of the previous section by using a lock so that the threads will be executed in sequence.

The first thread acquires the lock and performs its task while the other eight remain on hold. At the end of the execution of the first thread, that is, when the release() method is executed, the second one will get the lock and the threads from three to eight will still be waiting until the end of the execution (that is, once again, only after running the release() method).

The lock-acquire and lock-release execution are repeated until the ninth thread, with the final result that as a result of the lock mechanism, this execution takes place in a sequential mode, as can be seen in the following output:

---> Thread#1 running, belonging to process ID 10632
---> Thread#1 over
---> Thread#2 running, belonging to process ID 10632
---> Thread#2 over
---> Thread#3 running, belonging to process ID 10632
---> Thread#3 over
---> Thread#4 running, belonging to process ID 10632
---> Thread#4 over
---> Thread#5 running, belonging to process ID 10632
---> Thread#5 over
---> Thread#6 running, belonging to process ID 10632
---> Thread#6 over
---> Thread#7 running, belonging to process ID 10632
---> Thread#7 over
---> Thread#8 running, belonging to process ID 10632
---> Thread#8 over
---> Thread#9 running, belonging to process ID 10632
---> Thread#9 over

End

--- 47.3672661781311 seconds ---
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset