Frage zu Thread Synchronisation mit wait() und notify()

ralfb1105

Bekanntes Mitglied
Hallo,

ich bin ein Java Anfänger und versucche gerade vezweifelt folgendes Problem mit threads zu lösen.
Ich habe eine Main Klasse die einen Thread startet der darauf wartet eine Akion auszuführen wenn die Main Klasse es über ein Flag mitteilt. Im Prinzip funktioniert folgender Code:

public class Parent {
public static volatile boolean flag = false;

public static void main(String args[]) throws InterruptedException {
Runnable child = new Child();
Thread thread1 = new Thread(child);
//start child-thread
thread1.start();

LCD.drawString("Start main ...", 0, 2);
Delay.msDelay(6000);
LCD.drawString("Now start Beep ...", 0, 3);
Parent.flag = true;
LCD.drawString("Should Beep ...", 0, 4);
Delay.msDelay(20000);
Parent.flag = false;
LCD.drawString("Stop Beep ...", 0, 5);
}
}

class Child implements Runnable {

public void run() {
while (true) {
if (Parent.flag) {
for (double i=1; i<=9999999; i++) {
LCD.drawString("Beep " + i, 0, 0);
Delay.msDelay(1000);
if (!Parent.flag) {
break;
}
}
}
}
}
}


Da es sich in dem Thread "child" um eine Busy Loop handelt die CPU Zeit frisst, würde ich gerne den Thread warten lassen (wait) bis er mit notify informiert wird das sich jetzt etwas ändert, das flag wird auf true gesetzt.
Wenn das flag wieder auf false gesetzt wird soll der Thread sich wieder schlafen legen.

Ich habe einige Tutorials gefunden, wo es mit dem synchronized Monitor und wait()/notify() beschrieben wird. Leider muss ich zugeben das ich in keinem wirklich verstanden habe wo ich nun synchronized(object) setzen muss und wo genau wait() und notify().

Oder geht das etw nicht so und meine Lösung von oben ist so ausreichend und aus Java Sich hinreichend.

Für einen Lösungsansatz wäre ich SEHR DANKBAR!

Gruß

Ralf
 
Java:
public class Parent {
    public static volatile boolean flag = false;
   
    public static void main(String args[]) throws InterruptedException {
        Runnable child = new Child();
        Thread thread1 = new Thread(child);
        //start child-thread
        thread1.start();
            LCD.drawString("Start main ...", 0, 2);
            Delay.msDelay(6000);
            LCD.drawString("Now start Beep ...", 0, 3);
            Parent.flag = true;
            LCD.drawString("Should Beep ...", 0, 4);
            Delay.msDelay(20000);
            Parent.flag = false;
            LCD.drawString("Stop Beep ...", 0, 5);
    }
}

class Child implements Runnable {

    public void run() {
           while (true) {
               if (Parent.flag) {
                   for (double i=1; i<=9999999; i++) {
                       LCD.drawString("Beep " + i, 0, 0);
                       Delay.msDelay(1000);
                       if (!Parent.flag) {
                           break;
                       }
                   }
               }
           }
    }
}
 
Für sowas gibts echt viele Möglichkeiten. Hier mal was triviales (wenn auch nicht perfekt) nur zur Veranschaulichung:
Java:
public class Parent {
    public static volatile boolean flag = false;
    public static final Object lock = new Object();

    public static void main(String args[]) throws InterruptedException {
        Runnable child = new Child();
        Thread thread1 = new Thread(child);
        //start child-thread
        thread1.start();
        System.out.println("Start main ...");
        Thread.sleep(6000);

        System.out.println("Now start Beep ...");
        setFlag(true);

        System.out.println("Should Beep ...");
        Thread.sleep(20000);

        setFlag(false);
        System.out.println("Stop Beep ...");
    }

    static void setFlag(boolean b){
        flag = b;
        synchronized (lock){
            //Flag hat sich geändert -> Kind benachrichtigen
            lock.notify();
        }
    }
}

class Child implements Runnable {

    public void run() {
        try {
            for (int i = 0; i < Integer.MAX_VALUE; i++) {

                // Lock holen
                synchronized (Parent.lock) {
                    //Flag überprüfen
                    while (!Parent.flag) {
                        // Flag false ? -> Schlafen legen
                        Parent.lock.wait();
                    }

                    // Aufgeweckt worden und Flag = true -> Aktion ausführen
                    System.out.println("Beep " + i);
                    Thread.sleep(1000);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
Hallo Tarrew,

SUPER, vielen herzlichen Dank für Dein Beispiel wie so etwas zu implentieren ist! Das ist genau das was mir gefehlt hat um das Prinzip zu verstehen. Ich schaue es mir Morgen im Detail an aber auf den ersten schnellen Blick ist es schon mal einleuchtend 🙂

Falls ich doch noch eine Frage haben sollte schreibe ich es😉

Gruß

Ralf
 

Zurück
Oben