My problem is that the print order is not always as requested, and I wonder what I'm doing wrong.
I think your problem is that both the ping and pong threads are acquiring and releasing their own semaphore. I think you need to pass both semaphores to both threads. Each thread calls acquire()
on the acquireSemaphore
and release()
on the releaseSemaphore
.
acquireSemaphore.acquire();
System.out.println(message + "(" + i + ")");
releaseSemaphore.release();
The thread would look like:
public PlayPingPongThread (String msg, SimpleSemaphore acquireSemaphore,
SimpleSemaphore releaseSemaphore)
Then the threads are initialized as:
// ping acquires on the ping, releases the pong
PlayPingPongThread ping = new PlayPingPongThread("Ping!", pingSemaphore, pongSemaphore);
// pong acquires on the pong, releases the ping
PlayPingPongThread pong = new PlayPingPongThread("Pong!", pongSemaphore, pingSemaphore);
The pingSemaphore
should start with 1 permit and the pong one should start with 0.
ping
first callsacquire()
on thepingSemaphore
and it is given.ping
prints out ping.ping
callsrelease()
on thepongSemaphore
.- This wakes up
pong
(assuming your semaphore code works of course). pong
printspong
.pong
callsrelease()
on thepingSemaphore
.- repeat...