Verdammte Threads...:-!

strider

Mitglied
Halo an alle!
Ich habe ein Problem mit einer Aufgabe.
Ich muss die folgende Java code benutzen um dieses Ziel zu erreichen:
comandante_1 stellt eine Frage (immer als erstes), und soldatino_1 muss ihm antworten un dann auf Comandante_1 warten (Wait()).
Das Kode funktioniert bis ich :
ich ändere den Wert des Thread.sleep(500) (z.b. von 500 auf 5000)
und/oder
ich ändere die Reihenfolge in Main()
danach antworted das Programm nicht mehr (ich denke dass beide Threads sind im Wait(), auch wenn ich notifiyAll() nutze).
Ich bin neu in Java und brauche dringend Hilfe!
Danke an alle für euhre Hilfe!!
Strider

Java:
////////////////////////////////////////////////////

public class soldatino_1 implements Runnable 
{
     private final String[] ANSWERS = { "25", "2", "All of us are Sir!" };
     private int nextAnswer = 0;
     private comandante_1 mycomandante;
     
    public soldatino_1() 
    {
//        super();
    }
    
    /** Second Constructor */
    public soldatino_1(comandante_1 c_1) 
    {
//        super();
        mycomandante = c_1;
    }

     /** Sets the answer number */
    private synchronized void answerQuestion()
    {
        while(!mycomandante.isWaitingForAnswer())
        { 
            try
            {
                wait();
            }
            catch(InterruptedException e)
            {
                String errMessage = e.getMessage();
                System.out.println(errMessage);
            }
        }        
        nextAnswer = mycomandante.getNextQuestion();
        mycomandante.sir(); 
        System.out.println("soldatino (A" + nextAnswer + "):" + ANSWERS[nextAnswer]);    
        notifyAll();            
    }
    
    /** Override the Run method*/
    public void run()
    {
        for(int i = 0; i <3; i++)
        {
            try
            {
                Thread.sleep(500);
            }
            catch(InterruptedException e)
            {
                String errMessage = e.getMessage();
                System.out.println(errMessage);
            }                    
            answerQuestion();
        }
    }
}

//////////////////////////////////////////////

import java.util.Random;

public class comandante_1 extends Thread
{
    private final String[] Questions = { "How old are you?", "How many fitness tests have you taken?", "Are you prepared for the war?" };
    private int nextQuestion = 0;
    private Random generator = new Random();
    private boolean waitingForAnswer = false;
    
    /** Creates a new instance of comandante */
    public comandante_1() 
    {
//        super();
    }
    
    /** Returns an int value set randomly using the Random class */
    private int setNextQuestion()
    {
        int r = generator.nextInt(3);
        return r;
    }
    
    /** Sets the question number randomly using the setNextQuestion method */
    private synchronized void askQuestion()
    {           
        while(isWaitingForAnswer())
        {
            try
            {
                wait();
            }
            catch(InterruptedException e)
            {
                String errMessage = e.getMessage();
                System.out.println(errMessage);
            }
        }
        nextQuestion = setNextQuestion();
        setWaitingForAnswer(true);
        System.out.println("comandante (Q" + nextQuestion + "):" + Questions[nextQuestion]);
        notifyAll();              
    }
    
    /** Override the Run method*/
    public void run()
    {
        for(int i = 0; i <3; i++)
        {            
            try
            {
                Thread.sleep(500);
            }
            catch(InterruptedException e)
            {
                String errMessage = e.getMessage();
                System.out.println(errMessage);
            }                    
            askQuestion();
        }
    }
    
    // Private Setter method:
    private void setWaitingForAnswer(boolean b)
    {
        waitingForAnswer = b;
    }
    
    // Public method Sir:
    public void sir()
    {
        setWaitingForAnswer(false);
    }
    
    // Pubblic getter method:    
    public boolean isWaitingForAnswer()
    {
        return waitingForAnswer;
    }
        
    // Public method getNextQuestion:
    public int getNextQuestion()
    {
        return nextQuestion;
    }
}

////////////////////////////////////////////////////////////////////////

public class Main
{
   public static void main(String[] args) 
   {    
       Comandante_1 com_1 = new Comandante_1();
       Soldatino_1 sol_1 = new Soldatino_1(com_1);
       Thread thre_1 = new Thread(sol_1);   
       
       com_1.start();
       thre_1.start();

   }   
}
 
die beiden Threads bzw. der eine Thread und der eine Runnable synchronizisieren jeweils auf sich selber, waiten und notifyen dort je für sich,
wenn der comandante notify ausführt, bekommen das alle mit, die auf comandante waiten(), nicht die, die auf soldatino warten..

du brauchst ein gemeinsames Objekt x, auf welches beide synchronisieren, warten und notifyen,
im einfachen unsauberen Fall ein statische Objekt, von überall erreichbar,
besser aber ein nicht-statisches Objekt, beiden im Konstruktor übergeben,

oder es ist eines der beteiligten Objekte, der soldatino hat sowieso schon eine Referenz auf comandante,
dann bleibt der comandante wie er ist, nur der soldatino verwendet

synchronized(mycomandante) {
mycomandante.wait();
}
usw.
 
Hallo Slater vielen Dank für deine Antwort.
sorry aber Ich verstehe immer noch nicht ganz was du meinst, ich dachte das mycomandante ist schon ein gemeinsamer objekt (da ich com_1 im Main() als argumente zu Soldatino gegeben habe) und das meine WAIT() beide auf den Objekt Comandante referenzieren.
Ist es nicht so?
Sorry fals ich etwas dumm gefragt habe, aber ich bin ganz neu in Java...:noe:
 
Die Methode wait() bewirkt, dass der aktuelle Thread auf ein notify des Objekts wartet an dem wait() aufgerufen wurde.
Wenn Du also in einer Instanz von soldatino_1 einfach nur wait() aufrufst, bewirkt das, dass der aktuelle Thread wartet bis auf dieser Instanz eine notify() aufgerufen wird. Wenn der aktuelle Thread aber auf eine Benachrichtung einer Instanz von comandante_1 warten soll, musst Du eben an dieser Instanz wait() aufrufen, also in Deinem Fall mycomandate.wait() (s. SlaterB)

Ausführliche Erläuterung: Object#wait
 
OK sorry ich hab es nicht gesehen das in meine beispiel immer noch nur wait() stand, ich hatte es korrigiert wie empfohlen (myComandante.wait()) aber es geht trtzdem nicht, und das verstehe ich nicht, da myComandante referenziert auf Comandante_1.
Könnt ihr mich weiter helfen?
Danke
 
Fehlermeldung oder das gleiche alte Fehlverhalten zur Laufzeit?

in meinem Posting schrieb ich, was du außer dem wait-Aufruf noch alles ändern musst,
ist ja nicht so viel zu lesen

und poste am besten den neuen aktuellen Stand der soldatino-Klasse
 
Ok, zu erst entschuldig ich mich, a ich anscheined ein fehler gemacht habe (program is weiter in hintergrund gelaufen, und NetBeans hat komisch reagiret, und ich hatte keine veränderung gemerkt...sorry von ein Java newby!
Hier ist meine aktuelles Kode.
Wenn ich myComandante.wait() benutzte, ich erhalte eine fehlermeldung:

Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:485)
at tma03q1.Soldier_1_1.answerQuestion(Soldatino_1_1.java:34)
at tma03q1.Soldier_1_1.run(Soldatino_1_1.java:62)
at java.lang.Thread.run(Thread.java:619)

ich sehe dass das problem ist beim ausfuhren von myComandante.wait() aber verstehe nicht warum.

Danke für euhre hilfe.

Strider

Java:
public class Main
{
   public static void main(String[] args) 
   {    
       Comandante_1 com_1 = new Comandante_1();
       Soldatino_1 sol_1 = new Soldatino_1(com_1);
       Thread thre_1 = new Thread(sol_1);   
       com_1.start();
       thre_1.start();
   }   
} 

////////////////////////////////////////////////////

import java.util.Random;

public class Comandante_1 extends Thread
{
    private final String[] Questions = { "How old are you?", "How many fitness tests have you taken?", "Are you prepared for the war?" };
    private int nextQuestion = 0;
    private Random generator = new Random();
    private boolean waitingForAnswer = false;
    private boolean[] asked = {false, false, false};        
    
    /** Creates a new instance of Commander */
    public Comandante_1() 
    {
        
    }
    
    /** Returns an int value set randomly using the Random class */
    private int setNextQuestion()
    {
        int r = generator.nextInt(3);
        while(asked[r] == true)
        {
            r = generator.nextInt(3);
        }
        asked[r] = true;
        return r;
    }
    
    /** Sets the question number randomly using the setNextQuestion method */
    private synchronized void askQuestion()
    {           
        while(isWaitingForAnswer())
        {
            try
            {
                wait();
            }
            catch(InterruptedException e)
            {
                String errMessage = e.getMessage();
                System.out.println(errMessage);
            }
        }
        nextQuestion = setNextQuestion();
        setWaitingForAnswer(true);
        System.out.println("Commander (Q" + nextQuestion + "):" + Questions[nextQuestion]);
        notifyAll();              
    }
    
    /** Override the Run method*/
    public void run()
    {
        for(int i = 0; i <3; i++)
        {            
            try
            {
                Thread.sleep(50);
            }
            catch(InterruptedException e)
            {
                String errMessage = e.getMessage();
                System.out.println(errMessage);
            }                    
            askQuestion();
        }
    }
    
    // Private Setter method:
    private void setWaitingForAnswer(boolean b)
    {
        waitingForAnswer = b;
    }
    
    // Public method Sir:
    public synchronized void sir()
    {
        setWaitingForAnswer(false);
    }
    
    // Pubblic getter method:    
    public synchronized boolean isWaitingForAnswer()
    {
        return waitingForAnswer;
    }
        
    // Public method getNextQuestion:
    public int getNextQuestion()
    {
        return nextQuestion;
    }
}

////////////////////////////////////////////

public class Soldatino_1 implements Runnable 
{
     private final String[] ANSWERS = { "25", "2", "All of us are Sir!" };
     private int nextAnswer = 0;
     private Comandante_1 myCommander;
     
    public Soldatino_1() 
    {
        
    }
    
    /** Second Constructor */
    public Soldatino_1(Comandante_1 c_1) 
    {
          myCommander = c_1;
    }

     /** Sets the answer number */
    private synchronized void answerQuestion()
    {
        while(!myCommander.isWaitingForAnswer())
        { 
            try
            {
                myCommander.wait();
            }
            catch(InterruptedException e)
            {
                String errMessage = e.getMessage();
                System.out.println(errMessage);
            }
        }
        nextAnswer = myCommander.getNextQuestion();
        myCommander.sir();
        System.out.println("Soldier (A" + nextAnswer + "):" + ANSWERS[nextAnswer]);    
        notifyAll();            
    }
    
    /** Override the Run method*/
    public void run()
    {
        for(int i = 0; i <3; i++)
        {
            try
            {
                Thread.sleep(50);
            }
            catch(InterruptedException e)
            {
                String errMessage = e.getMessage();
                System.out.println(errMessage);
            }                    
            answerQuestion();
        }
    }
}
 
Zuletzt bearbeitet:
ich habe geschrieben
synchronized(mycomandante) {
mycomandante.wait();
}
eine dieser Zeilen hast du umgesetzt, die anderen beiden nicht..



synchronized(mycomandante) {

}
sollte am Anfang und Ende der Methode stehen, die ganze Aktion umfassen,
dafür kann das synchronized in der Methodensignatur weg
 
Hallo SlaterB, vielen Dank für deine Hilfe.
Icha habe mein answerQuestion() method so geändert:
Java:
        private void answerQuestion()
    {
        synchronized(myComandante){
        boolean test;
        test = myComandante.isWaitingForAnswer();
        while(!test)
        { 
            try
            {
                myComandante.wait();
            }
            catch(InterruptedException e)
            {
                String errMessage = e.getMessage();
                System.out.println(errMessage);
            }
        }
        nextAnswer = myComandante.getNextQuestion();
        myComandante.sir();
        System.out.println("Soldier (A" + nextAnswer + "):" + ANSWERS[nextAnswer]);    
        notifyAll();}
    }
und erhalte die folgende fehler:
Java:
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
        at java.lang.Object.notifyAll(Native Method)
        at tma03q1.Soldatino_1_1.answerQuestion(Soldatino_1_1.java:48)
        at tma03q1.Soldatino_1_1.run(Soldatino_1_1.java:65)
        at java.lang.Thread.run(Thread.java:619)
wenn ich notifyAll() allein synchroniziere:
Java:
    private synchronized void answerQuestion()
    {
        synchronized(myComandante){
        boolean test;
        test = myComandante.isWaitingForAnswer();
        while(!test)
        { 
            try
            {
                myComandante.wait();
            }
            catch(InterruptedException e)
            {
                String errMessage = e.getMessage();
                System.out.println(errMessage);
            }
        }
        nextAnswer = myComandante.getNextQuestion();
        myComandante.sir();
        System.out.println("Soldier (A" + nextAnswer + "):" + ANSWERS[nextAnswer]);}
        notifyAll();
    }
dann antwortet das Program wieder nicht mehr (waiting for ever).
 
OK SORRY, SORRY, SORRY, SORRY, SORRY, SORRY, SORRY, SORRY, SORRY, SORRY, SORRY, SORRY, SORRY, SORRY, SORRY, SORRY, SORRY, SORRY, SORRY, SORRY, SORRY, SORRY, SORRY, SORRY!

Es war wieder ein compilierung fehler von meine seite!!! Ich hatte diese variante schon probiert, aber Netbeans ist weiter im hintergrund gelaufen .... dann habe ich nur notifyAll() + synchronized, versucht...dann weiss ich auch nicht mehr...

Es sind 2 Tage das ich auf diese ver...te Frage arbeite (neben mein offizielles Job...) und bin ziemlich müde!!

Vielen Super herzlichen Dank für deine hilfe SlaterB und alle anderen auch und auch für den link!

Ciao

Strider
 

Neue Themen


Zurück
Oben