Threads synchronisieren von threads

Gustl_Java

Aktives Mitglied
Hallo, folgendes Programm:

Java:
public class HipHop extends Thread{

      String wort;
      long warte;

      HipHop(String wort, long warte){
            this.wort = wort;
            this.warte = warte;
      }

      public void run(){
            while (true){
                print_out(wort);
            }
      }
      
     public void print_out(String wort){
            System.out.print(wort);
            try{
                Thread.sleep(warte);
                //this.wait();
            }
            catch (InterruptedException ex){

            }
            //this.notify();
      }

      public static void main(String[] args) throws Exception{
            HipHop hip = new HipHop("Hip ",5000);
            HipHop hop = new HipHop("Hop ",1000);
            hip.start();
            hop.start();
            //hip.join();
            //hop.join();
      }
}

Im folgendem Programm wird in der Konsole dann hip und hop ausgegeben, hop 5x mehr als hip.
Jetzt will ich die erzeugenten Threads synchron machen.
Ich habe es so verstanden, dass bei der Methode print_out ein synchronized davorgeschrieben werden muss und hip.join(); und hop.join(); in der main, dann sollten sie synchron sein?

Wenn ich dies aber mache, wartet Hop nicht auf Hip, dann sollten sie sich doch genau abwechseln wenn sie synchron sind oder?
quasi so:
Java:
public class HipHop extends Thread{

      String wort;
      long warte;

      HipHop(String wort, long warte){
            this.wort = wort;
            this.warte = warte;
      }

      public void run(){
            while (true){
                print_out(wort);
            }
      }
      
      synchronized public void print_out(String wort){
            System.out.print(wort);
            try{
                Thread.sleep(warte);
                //this.wait();
            }
            catch (InterruptedException ex){

            }
            //this.notify();
      }

      public static void main(String[] args) throws Exception{
            HipHop hip = new HipHop("Hip ",5000);
            HipHop hop = new HipHop("Hop ",1000);
            hip.start();
            hop.start();
            hip.join();
            hop.join();
      }
}

Gruß
 
Nö.
Synchronized bedeutet nur, dass exakt ein Thread die ausgewiesene Methode betreten darf.
Die Reihenfolge wird nicht sichergestellt. Wie denn auch?
Der Scheduler weiß nicht dass sich die Threads auf jeden Fall abwechseln müssen.
Will sagen:
Du musst dir schon selbst überlegen, wie du garantierst dass sich die Threads abwechseln.
 
ahhh ok, das würde dann mit einer Variable gehn oder? Die überprüfe ich auf true und setze sie auf false, dann, wenn die Methode abgerabeitet ist, wieder auf true? mhh, werde ich mal testen.
War jetzt nur ein Blitzgedanke.

Danke dir.
Gruß
 

Zurück
Oben