I have been instructed to execute the pingpong game, which is called "ping" and "pong" correctly (meaning that there is no pong before ping) 10 times. The value of the final output in the console should be: "ping! (1)", "pong! (1)", "ping! (2)", "pong! (2)", etc.
The requirement is to implement gamepingpongthread using semaphores, blocking re-launch and countdown.
My problem is that the print order is not always requested, and I wonder what I'm doing wrong.
Here is the code:
import java.util.concurrent.Semaphore;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;
public class PingPongRight
{
static public class SimpleSemaphore
{
private int mPermits;
private ReentrantLock lock = new ReentrantLock();
private Condition isZero = lock.newCondition();
public SimpleSemaphore (int maxPermits)
{
mPermits = maxPermits;
}
public void acquire() throws InterruptedException
{
lock.lock();
while (mPermits == 0)
isZero.await();
mPermits--;
lock.unlock();
}
void release() throws InterruptedException
{
lock.lock();
try {
mPermits++;
isZero.signal();
} finally {
lock.unlock();
}
}
}
public static int mMaxIterations = 10;
public static CountDownLatch latch = new CountDownLatch(2);
public static class PlayPingPongThread extends Thread
{
private String message;
private SimpleSemaphore semaphore;
public PlayPingPongThread (String msg, SimpleSemaphore pingOrPong)
{
message = msg;
semaphore = pingOrPong;
}
public void run ()
{
for (int i = 1 ; i <= mMaxIterations ; i++) {
try {
semaphore.acquire();
System.out.println(message + "(" + i + ")");
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
latch.countDown();
}
}
public static void main(String[] args) {
try {
SimpleSemaphore pingSemaphore = new SimpleSemaphore(mMaxIterations);
SimpleSemaphore pongSemaphore = new SimpleSemaphore(mMaxIterations);
System.out.println("Ready...Set...Go!");
PlayPingPongThread ping = new PlayPingPongThread("Ping!", pingSemaphore);
PlayPingPongThread pong = new PlayPingPongThread("Pong!", pongSemaphore);
ping.start();
pong.start();
latch.await();
}
catch (java.lang.InterruptedException e)
{}
System.out.println("Done!");
}
}
Thanks in advance
source
share