Why this InnerThread isn't working properly? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 12

Why this InnerThread isn't working properly?

There is no error in this InnerThread program. But the problem is Thread should work one by one. One will put the value and then another will get value. But sometime put operation working two times in a row. Like... Put 0 Get 0 Put 1 Put 2 Get 1 Put 3 Get 2 So on... I already used wait() , notify(), synchronised method but didn’t worked. Here is the code👇 https://code.sololearn.com/ctKxpRr95419/?ref=app T.I.A

2nd May 2020, 6:39 PM
Arafat Hossain Ar
Arafat Hossain Ar - avatar
5 Answers
+ 4
Check this now, I made a few changes to your code and now its working. I only used notify and wait, nothing fancy. See comments in code and also a link to baeldung article that has the whole concept explained in detail. https://code.sololearn.com/ciexEj7Ck6Tj/?ref=app
3rd May 2020, 4:31 PM
Tibor Santa
Tibor Santa - avatar
+ 6
Thread.sleep() is not very exact with the wait time, and depends on the operating system's task scheduler to continue the program flow. Therefore your paralel threads may be "racing" and one of them could get ahead. To control the access to the shared resource (Q) you need to apply some locking mechanism, maybe look at Semaphore https://www.geeksforgeeks.org/semaphore-in-java/
2nd May 2020, 6:57 PM
Tibor Santa
Tibor Santa - avatar
+ 6
Tibor Santa Thank you so much It's working.😉
3rd May 2020, 5:44 PM
Arafat Hossain Ar
Arafat Hossain Ar - avatar
+ 5
Mirielle[Inactive] run this code on Netbeans or Eclipse. Sl code playground have limited execution time. But sometime put operation occurring after 10, 20 times.
3rd May 2020, 11:30 AM
Arafat Hossain Ar
Arafat Hossain Ar - avatar
+ 4
Tibor Santa It's not working, the reason is Semaphore used for multiple threads but it will first done one thread completely then moves to another. But I want, put will set the value and get should achieve that after putting. put, get....... this operation will continue until I stop the execution.
3rd May 2020, 5:38 AM
Arafat Hossain Ar
Arafat Hossain Ar - avatar