I'm trying to make 2 threads one Ping and one Pong. The idea is Ping should always execute first. I'm using synchronized methods. I'm not sure what is wrong with my code here. It looks to me like it should work. I have read up on a lot of documentation. So if you have anything that you think would be of help I'd be happy to read it. I'm sure it's something simple. Any Help Is appreciated
class Ping extends Thread {
private Table table;
private String text1 = "";
public Ping(Table t)
{
table = t;
}
public void run() {
for (int i = 0; i < 10; i++) {
text1= table.getPing();
System.out.println(text1);
}
}
}
class Pong extends Thread {
private Table table;
private String text1 = "";
public Pong(Table t)
{
table = t;
}
public void run() {
for (int i = 0; i < 10; i++) {
text1= table.getPong();
System.out.println(text1); }
}
}
class Table extends Thread {
private Table table;
private boolean pinged = false;
public synchronized String getPong() {
while (pinged == false) {
try {
//System.out.println("WAIT PONG");
wait();
}
catch (InterruptedException e)
{ }
}
pinged = false;
notifyAll();
String text = "pong";
return text;
}
public synchronized String getPing() {
while (pinged == true) {
try {
wait();
//System.out.println("WAIT PING");
} catch (InterruptedException e) { }
}
pinged = true;
notifyAll();
String text = "ping";
return text;
}
}
public class PingPong {
//private static final int WAIT_TIME = 200;
public static void main(String args[]) {
Table t = new Table();
Pong pong = new Pong(t);
Ping ping = new Ping(t);
System.out.println("main: starting threads...");
pong.start();
ping.start();
System.out.println("main: threads started, sleep a while " +
"and wait for termination of Ping and Pong");
System.out.println("both threads terminated");
}
}
Each result is different but the bizarre thing is I get repeats.
ping
pong
ping
ping
pong
pong
pong
ping
ping
ping
pong
pong
pong
ping
pong
ping
ping
pong
ping
pong