Skip to content

Instantly share code, notes, and snippets.

@smartkiwi
Created April 29, 2013 22:55
Show Gist options
  • Save smartkiwi/5485465 to your computer and use it in GitHub Desktop.
Save smartkiwi/5485465 to your computer and use it in GitHub Desktop.
PA1 Java
import java.util.concurrent.Semaphore;
public class PingPong {
private Semaphore ping_semaphore = new Semaphore(1, true), pong_semaphore = new Semaphore(1, true);
private int maxcount = 100;
class Ping implements Runnable {
@Override
public void run() {
for (int i = 0; i < maxcount; i++) {
try {
ping_semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
System.out.println("Ping!");
pong_semaphore.release();
}
}
}
class Pong implements Runnable {
@Override
public void run() {
for (int i = 0; i < maxcount; i++) {
try {
pong_semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
System.out.println("Pong!");
ping_semaphore.release();
}
}
}
public void mainCycle() {
try {
pong_semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Thread ping = new Thread(new Ping());
ping.start();
Thread pong = new Thread(new Pong());
pong.start();
try {
ping.join(100000);
pong.join(100000);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
public static void main(String[] args) {
System.out.println("Ready... Set... Go!");
PingPong t = new PingPong();
t.mainCycle();
System.out.println("Done");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment