Forums Register Login

Inter thread communication woes

+Pie Number of slices to send: Send
I have been exploring the concept of inter thread communication & wrote the following program to test my understanding based on the producer consumer problem given in a reference book by Herbert Schildt.



Even though the program runs as expected but it never prints the statements preceding wait(). How exactly is the program executing ?
+Pie Number of slices to send: Send
I haven't read the entire code or ran it myself, but my guess is that the first thread skips the while loop, executes and flips the switch before the second thread starts. Hence the second thread also jumps the while loop and the program ends.
+Pie Number of slices to send: Send
Is there anything I can add/remove from my program to avoid the anomaly. Moreover, the program's output is in the sequence of values being calculated & then stored for all iterations. How is that occurring if the wait call is not being executed at all ?
+Pie Number of slices to send: Send
Try reversing the order in which you instantiate and start the threads
+Pie Number of slices to send: Send
 

David O'Meara wrote:Try reversing the order in which you instantiate and start the threads


If there's a problem that depends on the timing of the threads, then reversing the order in which you instantiate and start the threads is in principle not going to solve the problem; it might appear to work, but when you run it a next time, you might get the problem again. The order in which threads are scheduled is unpredictable; when you start T1 and T2, then T2 might be scheduled to run before T1. The unpredictability is one of the things that makes multi-threaded programming so hard...

edit I ran your program (in NetBeans) and got the following output. Does it not produce any output when you run it?


Calculated to 3

Waiting in calculate

Stored at arr[0] = 3

Waiting in store

Calculated to 5

Waiting in calculate

Stored at arr[1] = 5

Waiting in store

Calculated to 7

Waiting in calculate

Stored at arr[2] = 7

Waiting in store

Calculated to 9

Waiting in calculate

Stored at arr[3] = 9

Waiting in store

Calculated to 11

Waiting in calculate

Stored at arr[4] = 11

Waiting in store

Calculated to 13

Waiting in calculate

Stored at arr[5] = 13

Waiting in store

Calculated to 15

Waiting in calculate

Stored at arr[6] = 15

Waiting in store

Calculated to 17

Stored at arr[7] = 17

 
this llama doesn't want your drama, he just wants this tiny ad for his mama
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 740 times.
Similar Threads
Synchronous objects.
Important, about threads
thread.wait or object.wait
threads synchronization problem
Parallel running quicksort
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 01:57:23.