Java-Thread-Ping-Pong-Beispiel

Ich versuche zu verstehen Gewinde Grundlagen, und als erstes Beispiel erstelle ich zwei thread, die schreiben, die einen String auf der Standardausgabe ausgegeben. Ich weiß der scheduler ermöglicht die Ausführung der threads mit einer round-robin-Zeitplan. Thats, warum ich habe:

PING
PING
pong
pong
pong
PING
PING
PING
pong
pong

Nun möchte ich eine shared-variable, so dass jeder thread wird wissen, wenn seine Ihre umdrehung:

public class PingPongThread extends Thread {
private String msg;
private static String turn;

public PingPongThread(String msg){
    this.msg = msg;
}
@Override
public void run() {
    while(true) {
        playTurn();
    }

}
public synchronized void playTurn(){
    if (!msg.equals(turn)){
        turn=msg;
        System.out.println(msg);
    }
}
}

Main-Klasse:

public class ThreadTest {
    public static void main(String[] args) {
        PingPongThread thread1 = new PingPongThread("PING");
        PingPongThread thread2 = new PingPongThread("pong");
        thread1.start();
        thread2.start();
    }
}

Ich synchronisiert, die "turn-manager", aber ich bekomme immer noch so etwas wie:

PING
PING
pong
pong
pong
PING
PING
PING
pong
pong

Kann jemand erklärt, was ich bin fehlt, und Warum bekomme ich nicht die Ping-pong... ping pong.
Danke!

wie ist die Wende manager implementiert ?
Von "biegen-manager" meine ich public synchronized void playTurn()

InformationsquelleAutor Kummo | 2012-10-08

Schreibe einen Kommentar