30 May 2010 22:15:14 GMT, /Stefan Ram/:
Eric Sosman<esosman@ieee-dot-org.invalid> writes:
Thread.yield() is better than Thread.sleep() because it "notices"
the change of state sooner.
Some years ago in de.comp.lang.java, some people told me,
Thread.yield() was effectively a no-operation, so one should
never use it.
I've recently experimented with implementing (Java 1.4 compatible)
asynchronous I/O for copying files using two threads just to see if it
could be any better than FileChannel.transferTo(). I've basically tried
to read into a buffer in one thread, next write it out in another, while
the reading thread fills in a second buffer to be written next.
Because I've not put much effort into it and I've not done my
synchronization quite right the whole thing basically ended in reading
the whole input while writing quite small (non-consecutive) part of it.
Using Thread.yield() in the reading thread after reading a block of
input made the operation complete normally for me because it gave chance
to the writing thread perform some preconditions for the synchronization
I was relying to.
However, as Eric Sosman has pointed out in another reply, Thread.yield()
is not a way to achieve synchronization because if there are more (most
probably unrelated) threads, it is not guaranteed which one of them will
be run after pausing the current thread. But it does work (is not a NOP)
and I think it could be used as minor hint for fine-tuning heavy
background processes and the like.
you did the synchronization improperly. I'd rather do a proper
implementation which does not need such hacks. My 0.02EUR.