|
My main question to this, is how strictly the "interleaving" has to be prevented?
Should it be that all 100 "AAAA" come before any "BBBB"?
Or is it only that you should not get any blocks such as "AAAAAAAABBBBBBBBB" followed by two newlines (which could and would definately happen with the way that is written).
If the second case, then, of course, the synchronized block must be around only the two print statements and not around the while loop. Or a synchronized around the while with notify and wait positioned around the prints (but that could also, easily lead to hung threads).
Better would be the "new" concurrent package and to obtain a lock on the object directly before printing and release it directly after printing (or directly before and after the while loop if the first case).
And, regardless of which it is, the object on which they are synchronizing must be the same Object visible from both classes, which will mean a larger change to the code to provide that Object in such a way that both have access to it (hopefully without it being some public static object inside of ThreadTest).
|