Page 1 of 6 123 ... LastLast
Results 1 to 20 of 116
  1. #1
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,025
    Rep Power
    8

    Default Once again: waiting in a thread loop.

    (Or how to get into one and, most importantly, how to get out of a one.)
    I haven’t seen any better alternative to my previous loop constructions! Maybe because loops form the very hearth of computers and there functioning. Almost everything, concerning a computer, is loop cycle; a program is one the processor cycle is one, events are loops… the poor thing has actually noting better to do than spinning its loops (I know, now that nick is reading carefully- – he thinks that I am joking, but I am not, this looping bossiness is very serious to me… so he will “surprise” me with another mysterious code which should put my thinking into a loop (because he is actually the joker of our forum).

    So here is another example, but this time, norm’s question “when you get out of it, what than??? (note, the question marks… norm is really curious here… or maybe upset?) should be answered better this time:

    This new loop waits for the sound tracks to start and is note at the GUI class where buttons etc. are pushed. It sits at the class where all the sounblocks are. The loop happens, again, inside a thread (I start to like threads), so here it is:

    Java Code:
    class Waitloop extends Thread {
       
            public Waitloop() {  // the thread counter
                cnt++;
                System.out.println("count wait thread " + cnt); // to see what it is looping
            }
                public void run() {  
                    cont.setstartFlag(false);
                    
                    do  {                 
                           
                    } while (!cont.getstartFlag());              
                    cont.setstartFlag(false);
                    System.out.println("exit thread " + cnt);
                    mainSoundblock(1);
                }
        }
    The loop will keep the thread busy spinning until the method call of the GUI class turns true. Than the flag gets reset and the important mainSoundblock(1); method starts WITHIN THE THREAD.
    Consider the working of this method similar to a pin-ball machine. The little ball starts at the very top but eventually will reach the bottom. The if’s, when turn false, will push the ball hard (the esc key was pressed). Each soundblock takes from 20 sec. to several minutes (depending on midi pedals, remember). When reaching the end the thread is over and the cycle/ thread repeats by pushing the start button.

    Java Code:
    private void mainSoundblock(int trck)  {
        cont.ed.resetFbo();
        if (trck==1 && !cont.getescFlag())  {
        Soundblock1();
        cont.settrackNumb(trck);
        trck=2;
        }
        else
        if (trck==2 && !cont.getescFlag())  {
        Soundblock2();
        cont.settrackNumb(trck);
        trck=3;
        }
        else
        if (trck==3 && !cont.getescFlag())  {
        Soundblock3();
        cont.settrackNumb(trck);
        trck=4;
        }
        else
        if (trck==4 && !cont.getescFlag())  {
        Soundblock4();
        cont.settrackNumb(trck);
        trck=5;
        }
        else
        if (trck==5 && !cont.getescFlag())  {
        Soundblock5();
        cont.settrackNumb(trck);
        trck=6;
        }
        else
        if (trck==6)  {
        Soundblock6();
        exit();
        cont.settrackNumb(trck);
        trck=7;
        }
        else
        if (trck==7 && !cont.getescFlag())  {
        Soundblock7();
        cont.settrackNumb(trck);
        trck=8;
        }
        else
        if (trck==8)  {
        Soundblock8();
        cont.settrackNumb(trck);
        trck=9;
        }
        else
        if (trck==9 && !cont.getescFlag())  {
        Soundblock9();
        exit();
        cont.settrackNumb(trck);
        trck=10;
        }
        else
        if (trck==10 && !cont.getescFlag())  {
        Soundblock10();
        cont.settrackNumb(trck);
        trck=11;
        }
        else
        if (trck==11 && !cont.getescFlag())  {
        Soundblock11();
        cont.settrackNumb(trck);
        trck=12;
        }
        else
        if (trck==12 && !cont.getescFlag())  {
        Soundblock12();
        cont.settrackNumb(trck);
        trck=1;
        }
        System.out.println(" final of sound block " );
       cont.setescFlag(false);
       cont.ed.closeFbo1();
       cont.stopclk(); 
    }

  2. #2
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,025
    Rep Power
    8

    Default

    By the way PK, when coming out of the loop and NOT coming out of the thread, all the buttons, besides the escape, are turned off (xxx.setEnabled(false);) so that no other thread, besides the midipedal and escape, can disturb the pin ball.

  3. #3
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,025
    Rep Power
    8

    Default

    this funny head appeared by itself?

  4. #4
    Supamagier is offline Senior Member
    Join Date
    Aug 2008
    Posts
    384
    Rep Power
    6

    Default

    nice, and yes, it did you probably tried
    Java Code:
    (xxx.setEnabled(false);)
    where the ; ) turns into that smiley :)
    I die a little on the inside...
    Every time I get shot.

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,548
    Rep Power
    23

    Default

    The question still is: why can't you start a thread that calls mainSoundblock(1); when/where the cont.getStartFlag() flag is set?
    Why spin in a loop waiting for an event before calling a method, when the event itself could start a thread to call the method?
    The setting and testing and reseting of the flag is a great waste of time and code.

  6. #6
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,025
    Rep Power
    8

    Default

    Yes norm, we might get to the center of this problem (maybe a lack of java imagination of mine). Java does not support multiple inheritance, right. I red some stuff about that, and the point I got out of that all, is that they do not want to turn java into the spaggetti-code mess of C++. I started out with java and do not know any better, good! (I choose for java, because I do not feel any sympathy for the micro-soft (Chicago) software-boys – if you want to know more about that, read Naomi Klein’s latest, The Shock Doctrine (yes, nick I believe we should show our code-biting-juniors about the many hidden background stories of this world).
    Okay let’s follow the thread, when the Main class on top of the other classes creates an instance of the second Controler class, that has all the GUI stuff, THERE IS A ONE WAY DIRECTION OF INFORMATION, right. When the instance of the GUI-class, called “cont”, created at the Main-class (where all the soundblocks are, remember) wants to get data from the GUI-class it gets it by cont.whatever(); If I create a thread at one of the event-notifying methods (of the GUI-class) I WOULD BE GOING INTO THE OPPOSITE DIRECTION. Nick, got that problem (I should say he is smart), but his code is any good….. is it? (do { } while (codeofNick( true/false); Nick you should NOT crunch first-years students of English with Shakespeare!

  7. #7
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,025
    Rep Power
    8

    Default

    In case you haven't followed other similar threaeds
    the code and text of nick:

    class A {
    B b;
    A(B bee){
    b = bee;

    Class A now can do and call methods of a class B on the name "b" thus:

    b.doSomething(data);

    In the class that has the button pushing stuff, we have a remarkably simple adjunct but that requires you grasp this first,.... then we still have to drive the controller class in a non-blocked manner using the clock I described in the don't ask me to which you refer.

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,548
    Rep Power
    23

    Default

    Where is the instance of the Waitloop class created?

    Another idea. Change the run method in Waitloop as follows:
    Java Code:
      public void run() {  
                    cont.returnWhenICanExecute(this);
                    mainSoundblock(1);
                }
    The returnWhenICanExecute method would loop/wait until the event occured when you want the mainSoundblock method to be called. This would simplify the design by not requiring the run method to know about setting and clearing flags in the cont class.
    Last edited by Norm; 09-02-2008 at 03:52 PM.

  9. #9
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,025
    Rep Power
    8

    Default

    Mozart did not like the flute and when he was asked what he considers worse, he answered two flutes!

    Finale I have the the program working. I have tested the application many times and everything works just fine. I have to take care of some esthetical things.... and done.

    Probably the underlaying mistake of the program is that I did not put the GUI stuff into the top class. I have two waitloops taking care of the GUI management, and one in a new created thread. (PK, I did synchronize some method concerning your remark)

    Java Code:
    private void waitloop()  {
      
       wl = new Waitloop();
       wl.start();
       cont.setstartFlag(false);
       cont.selectonoff(true);
       start=false;
      
       do   { } while (!start);             // wait for start button 
            int trc = cont.gettrackNumb();  // read out the track number
            mainSoundblock(trc);
     
    }
    
    
    class Waitloop extends Thread {
       
            public Waitloop() {  
                cnt++;                                          // the thread counter
                System.out.println("count wait thread " + cnt); // to see what it is looping
            }
                public void run() {  
                    cont.setstartFlag(false);
                    
                    do  {                 
                           
                    } while (!cont.getstartFlag());          // read the start button           
                    start=true;
                    System.out.println("exit thread " + cnt);
                    
                }
    }
    
    
      
    
    
    private void mainSoundblock(int trck)  {
        cont.ed.resetFbo();
        cont.setescFlag(false);
        trig=false; exit=false;
        if (trck==1 && !cont.getescFlag())  {
        Soundblock1();
        cont.settrackNumb(trck);
        trck=2;
        }
        
        if (trck==2 && !cont.getescFlag())  {
        Soundblock2();
        cont.settrackNumb(trck);
        trck=3;
        }
        
        if (trck==3 && !cont.getescFlag())  {
        Soundblock3();
        cont.settrackNumb(trck);
        trck=4;
        }
        
        if (trck==4 && !cont.getescFlag())  {
        Soundblock4();
        cont.settrackNumb(trck);
        trck=5;
        }
    
        ....... etc until 12
    
       System.out.println(" end of sound block " );
       cont.setescFlag(false);
     //  cont.ed.closeFbo1();
       cont.stopclk();
       cont.ed.resetFbo();
        waitloop();
    }

    Sure next programming project I should design differently and I will try to get rid of those un-elegant cpu consuming loops.

    Two more questions
    1) when appending text into a JTextArea, how could I keep the new text on sight at the screen (the new appended text scrolls down and disappears)?
    2) Before going out of the application, at the very last moment, I would like to clean up some things (clossing drivers etc.). I am using the standard

    window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

    to exit.

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,548
    Rep Power
    23

    Default

    WOW. You have 2 dead,useless loops!

    Before going out of the application
    Don't use EXIT_ON_CLOSE.
    Use a Window Listener to catch window closing and put a call to your cleanup code there.

  11. #11
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,025
    Rep Power
    8

    Default

    ok.
    .......... than I am going to need another loop?

  12. #12
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,025
    Rep Power
    8

    Default

    There is something I am not getting here!


    Class A //sound blocks data

    B b = new B();

    b.whateverMethod(); //of class B



    Cass B extends JPanel //GUI listeners buttons etc.


    There happens an event in class B (at any time!!!) how this can be noted in A???

    e.g. listener sets boolean midipedal to true

    public boolean getMidiped() { // at class B
    return midipedal;
    }

    At class A I could ask for b.getMidiped() and it will return the correct true or false of the var. BUT I DO NOT KNOW WHEN THAT WILL HAPPEN FROM INSIDE THE CODE OF CLASS A SO THAT IS WHY I NEED A LOOP TO WAIT THIS TO HAPPEN......... OR NOT???

  13. #13
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,025
    Rep Power
    8

    Default

    do {

    I am trapped in a loop...... who can help me out

    } while(who?);

  14. #14
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    7

    Post this funny head appeared by itself?

    Quote Originally Posted by willemjav View Post
    the many hidden background stories of ..
    I was busy yesterday, finally got a script to run late at night so I did not have time to crawl your code. You have, however you got there, arrived at the central issue on threading - do not know when something will happen - and there lay the keys to your code design. Spin loops are generally considered to waste processor power, thus whether sleep and yield work correctly become central design issues. Unfortunately, robust design of para-realtime scheduling is beyond contemporary practice in Java.

    Sun Java Real-Time System - Mediacasts

    Efforts are in place to achieve a more robust wording that scales to mainframe.

    Dr. Doug Locke may have some advanced observations if you wish to study the matter. Bascially, use synchronized, do not try to do it with bumping priorities. Choose one class, ala hardwired's recent post in the other thread, to be your main class - which should somehow account for button pushing in the GUI - my design has a clock in a hard spin, we do if ( boolean ) in that class ( instance ? ) and manipulate that boolean from the controller class ... we can think of the clock as a Propogator, but you can call me Alligator. ( ! )
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  15. #15
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,548
    Rep Power
    23

    Default Replacement of loop with wait and notify

    I took your posted code, made it into something that would execute and then modified it to use wait and notify:
    First is your code with some dummy stuff:
    Java Code:
    // willemjav looping problem
    
    public class WaitLoops {
       boolean start;
       Cont cont;
       Waitloop wl;
    
       //-----------------------------------------------------------
       // Wait until start set
       private void waitloop()  {
         
          wl = new Waitloop();
          wl.start();
          cont.setstartFlag(false);
    //      cont.selectonoff(true);
          start=false;
          System.out.println(">>waitloop - entering loop");
          do   { } while (!start);        // wait for start button 
          System.out.println(">>waitloop - exited loop");
       
          int trc = cont.gettrackNumb();  // read out the track number
          mainSoundblock(trc);
        
       } // end waitloop()
       
       int cnt;
    
       //-------------------------------------------------------------------------
       // Wait until StartFlag set
       class Waitloop extends Thread {
            
            public Waitloop() {  
                cnt++;                                          // the thread counter
                System.out.println("count wait thread " + cnt); // to see what it is looping
            }
            public void run() {  
                 cont.setstartFlag(false);
                 
                 do  { } while (!cont.getstartFlag());          // read the start button 
              
                 start=true;   // release waitloop looping
                 System.out.println("exited thread " + cnt);
                 
            }
       } 
    
       class Cont  {
          boolean flag;
          boolean esc;
          int tn;
    
          boolean getstartFlag(){return flag;}
          void setstartFlag(boolean f){
              flag = f;
              System.out.println("set start flag " + flag);
          }
    
          int gettrackNumb() {return tn;}
          void settrackNumb(int trck) {tn = trck;}
    
          boolean getescFlag() {return esc;}
          void setescFlag(boolean f) {esc = f;}
       }
      
    
    
       private void mainSoundblock(int trck)  {
    //       cont.ed.resetFbo();
           cont.setescFlag(false);
    //       trig=false; 
    //       exit=false;
    
           if (trck==1 && !cont.getescFlag())  {
           Soundblock1();
           cont.settrackNumb(trck);
           trck=2;
           }
           
           if (trck==2 && !cont.getescFlag())  {
           Soundblock2();
           cont.settrackNumb(trck);
           trck=3;
           }
           
           if (trck==3 && !cont.getescFlag())  {
           Soundblock3();
           cont.settrackNumb(trck);
           trck=4;
           }
           
           if (trck==4 && !cont.getescFlag())  {
           Soundblock4();
           cont.settrackNumb(trck);
           trck=5;
           }
       
       //    ....... etc until 12
       
          System.out.println(" end of sound block " );
          cont.setescFlag(false);
    
        //  cont.ed.closeFbo1();
    //      cont.stopclk();
    //      cont.ed.resetFbo();
           waitloop();             // NCR - RECURSIVE CALL???
       } // end mainSoundBlock
       void Soundblock1(){}
       void Soundblock2(){}
       void Soundblock3(){}
       void Soundblock4(){}
    
       // Constructor --------------------------------
       public WaitLoops() {
          cont = new Cont();
          // Start a thread to set flag in 2 seconds
          Thread t = new Thread(new Runnable() {
             public void run() {
                for(int i=0; i < 5; i++) {
                   try{Thread.sleep(2000);}catch(Exception x){}
                   cont.setstartFlag(true);  // release Waitloop thread looping
                } // end for(i)
                System.exit(0);  // EXIT - END OF TEST
             }
          });
          t.start();
          waitloop();
       }
       //--------------------------------------------------------------------
       // Test the above
       public static void main(String[] args) {
          new WaitLoops();
       }
    } // end class
    
    /*
    Running: "C:\Program Files\Java\j2re1.4.2_08\bin\java.exe" -cp D:\JavaDevelopment\Testing\JavaForum\;D:\JavaDevelopment;. WaitLoops
    
    count wait thread 1
    set start flag false
    >>waitloop - entering loop
    set start flag false
    set start flag true       <<<<<<< After 2 sec sleep
    exited thread 1
    >>waitloop - exited loop
     end of sound block 
    
    count wait thread 2
    set start flag false
    >>waitloop - entering loop
    set start flag false
                          >>>>>>>>>>> HERE I C+A+D and ended task
    0 error(s)
    */
    Then modified to use wait / notify
    Java Code:
    // willemjav looping problem - Changed to use wait() and notifyAll()
    
    public class WaitLoops2 {
       Cont cont;
       int cnt;
    
       //-----------------------------------------------------------
       // Wait until "user" presses start button (uses getstartFlag)
       private void waitloop()  {
          while(true) {  // do loop here vs a recursive call from mainSoundblock
             cnt++;
             Object mon = cont.setstartFlag(false);  // be sure flag is off / get monitor
       //      cont.selectonoff(true);
             System.out.println(">>waitloop - entering loop " + cnt);
             while(!cont.getstartFlag()) {
                synchronized(mon) {
                   try{mon.wait();}catch(Exception x){}  // wait until button pressed
                }
             }
             System.out.println(">>waitloop - exited loop " + cnt);
          
             int trc = cont.gettrackNumb();  // read out the track number
             mainSoundblock(trc);
          }
       } // end waitloop()
       
       //----------------------------------------------------
       // Dummy class for testing
       class Cont  {
          boolean flag;
          boolean esc;
          int tn;
          Object mon = new Object();
    
          boolean getstartFlag(){
             return flag;
          }
          Object setstartFlag(boolean f){
              flag = f;
              System.out.println("set start flag " + flag);
              if(flag) {    // when flag is set, release those waiting
                synchronized(mon) {
                   mon.notifyAll();  // wakeup waiting thread
                }
              }
              return mon;  // return monitor so caller can wait() on it
          }
    
          int gettrackNumb() {return tn;}
          void settrackNumb(int trck) {tn = trck;}
    
          boolean getescFlag() {return esc;}
          void setescFlag(boolean f) {esc = f;}
       }
      
    
    
       private void mainSoundblock(int trck)  {
    //       cont.ed.resetFbo();
           cont.setescFlag(false);
    //       trig=false; 
    //       exit=false;
    
           if (trck==1 && !cont.getescFlag())  {
           Soundblock1();
           cont.settrackNumb(trck);
           trck=2;
           }
           
           if (trck==2 && !cont.getescFlag())  {
           Soundblock2();
           cont.settrackNumb(trck);
           trck=3;
           }
           
           if (trck==3 && !cont.getescFlag())  {
           Soundblock3();
           cont.settrackNumb(trck);
           trck=4;
           }
           
           if (trck==4 && !cont.getescFlag())  {
           Soundblock4();
           cont.settrackNumb(trck);
           trck=5;
           }
       
       //    ....... etc until 12
       
          System.out.println(" end of sound block " );
          cont.setescFlag(false);
    
        //  cont.ed.closeFbo1();
    //      cont.stopclk();
    //      cont.ed.resetFbo();
           if(cnt == 4) {      // debug to show recursive calls - NONE with this code
             try{throw new Exception("Show Call Stack");}catch(Exception x){x.printStackTrace();}
                /*
                java.lang.Exception: Show Call Stack
                	at WaitLoops2.mainSoundblock(WaitLoops2.java:97)
                	at WaitLoops2.waitloop(WaitLoops2.java:23)
                	at WaitLoops2.<init>(WaitLoops2.java:123)
                	at WaitLoops2.main(WaitLoops2.java:129)
                */
           }
       } // end mainSoundBlock
       // Dummy methods
       void Soundblock1(){}
       void Soundblock2(){}
       void Soundblock3(){}
       void Soundblock4(){}
       // ...
    
       // Constructor --------------------------------
       public WaitLoops2() {
          cont = new Cont();
    
          // Start a thread to set flag in 2 seconds
          // This is to simulate user pressing a button
          Thread t = new Thread(new Runnable() {
             public void run() {
                for(int i=0; i < 5; i++) {
                   try{Thread.sleep(2000);}catch(Exception x){}
                   cont.setstartFlag(true);  // press button
                } // end for(i)
                System.exit(0);  // EXIT - END OF TEST
             }
          });
          t.start();
    
          waitloop();                      // Start the program process
       }  // end Constructor
    
       //--------------------------------------------------------------------
       // Test the above
       public static void main(String[] args) {
          new WaitLoops2();
       }
    } // end class
    
    /*
    Running: "C:\Program Files\Java\j2re1.4.2_08\bin\java.exe" -cp D:\JavaDevelopment\Testing\JavaForum\;D:\JavaDevelopment;. WaitLoops2
    
    set start flag false
    >>waitloop - entering loop 1
    set start flag true
    >>waitloop - exited loop 1
     end of sound block 
    
    set start flag false
    >>waitloop - entering loop 2
    set start flag true
    >>waitloop - exited loop 2
     end of sound block 
    
    set start flag false
    >>waitloop - entering loop 3
    set start flag true
    >>waitloop - exited loop 3
     end of sound block 
    
    set start flag false
    >>waitloop - entering loop 4
    set start flag true
    >>waitloop - exited loop 4
     end of sound block 
    
    java.lang.Exception: Show Call Stack
    	at WaitLoops2.mainSoundblock(WaitLoops2.java:97)
    	at WaitLoops2.waitloop(WaitLoops2.java:23)
    	at WaitLoops2.<init>(WaitLoops2.java:123)
    	at WaitLoops2.main(WaitLoops2.java:129)
    set start flag false
    >>waitloop - entering loop 5
    set start flag true
    >>waitloop - exited loop 5
     end of sound block 
    set start flag false
    >>waitloop - entering loop 6
    
    0 error(s)
    
    */

  16. #16
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,025
    Rep Power
    8

    Default

    Thanks norm, I'll need some time to study all that

  17. #17
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,548
    Rep Power
    23

    Default

    Your design seems backwards. Normally the GUI class is instantied first and starts the worker class (to do any init it needs) and then exits to let the GUI engine wait for user input. When the user does something, a listener is called which then calls(via a new Thread) the worker class to do whatever needs to be done.
    Here's a new version of your program configured to work that way:
    Java Code:
    // willemjav looping problem - Add GUI to call mainSoundblock at button press
    
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    
    public class WaitLoops3 extends JFrame implements ActionListener {
       JButton doItBtn = new JButton("Do it");
       Cont cont;
       int cnt;
      
       //----------------------------------------------------
       // Dummy class for testing
       class Cont  {
          boolean esc;
          int tn = 1;
    
          int gettrackNumb() {return tn;}
          void settrackNumb(int trck) {tn = trck;}
    
          boolean getescFlag() {return esc;}
          void setescFlag(boolean f) {esc = f;}
       } // end class Cont
      
        public void actionPerformed(ActionEvent ae) {
          Object obj = ae.getSource();
          if(obj == doItBtn) {
             // Start task on own thread
             Thread t = new Thread(new Runnable() {
                public void run() {
                   mainSoundblock(cont.gettrackNumb());
                }
             });
             t.start();
    
          }else {
             System.out.println("unknown ae" + ae);
          }
       } // end actionPerformed
       //------------------------------------------------------
       private void mainSoundblock(int trck)  {
    //       cont.ed.resetFbo();
           cont.setescFlag(false);
    //       trig=false; 
    //       exit=false;
    
           if (trck==1 && !cont.getescFlag())  {
           Soundblock1();
           cont.settrackNumb(trck);
           trck=2;
           }
           
           if (trck==2 && !cont.getescFlag())  {
           Soundblock2();
           cont.settrackNumb(trck);
           trck=3;
           }
           
           if (trck==3 && !cont.getescFlag())  {
           Soundblock3();
           cont.settrackNumb(trck);
           trck=4;
           }
           
           if (trck==4 && !cont.getescFlag())  {
           Soundblock4();
           cont.settrackNumb(trck);
           trck=5;
           }
       
       //    ....... etc until 12
       
          System.out.println(" end of sound block @ " + System.currentTimeMillis() );
          cont.setescFlag(false);
    
    //      cont.ed.closeFbo1();
    //      cont.stopclk();
    //      cont.ed.resetFbo();
       } // end mainSoundBlock
    
       // Dummy methods
       void Soundblock1(){System.out.println("Soundblock1");}
       void Soundblock2(){System.out.println("Soundblock2");}
       void Soundblock3(){System.out.println("Soundblock3");}
       void Soundblock4(){System.out.println("Soundblock4");}
       // ...
    
       // Constructor --------------------------------
       // Build the GUI and wait for user's input
       public WaitLoops3() {
          super("Do it when button pressed");
          cont = new Cont();
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          Container pane = getContentPane();
          JPanel panel = new JPanel();
          doItBtn.addActionListener(this);
          panel.add(doItBtn);
          pane.add(panel);
          pack();
          setLocation(300, 200);  // move out of corner
          setVisible(true);
       }  // end Constructor
    
       //--------------------------------------------------------------------
       // Test the above
       public static void main(String[] args) {
          new WaitLoops3();
       }
    } // end class

  18. #18
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    7

    Post do{}while(); is not wait() / notifiy()

    Quote Originally Posted by willemjav View Post
    (Or how to get into one and, most importantly, how to get out of a one.)
    Really simple:
    Java Code:
    class Music implements List of Some Kind{
        List notes;
        Position position;
        Boolean playing;
        Music(){
            // ....? maybe set music type or something
        }
        public void nextNote()
        {
            ++position;
        }
    }
    //
    //
    class Controller extends GUI / AWT / Graphical {
        Button goButton;
        Button stopButton;
        Boolean ExitProgram; // Actually, you do not need this
        //
        MasterClock mc;
        //
        Controller(MasterClock mc){
            this.mc = mc;
        }
        public void ButtonHandler(ButtonPush bp)
        {
            if(bp == goButtonPush)
            {
                mc.startPlay();
            }
            if(bp == stopButtonPush)
            {
                mc.stopPlay();
            }
        }
        public void stopPlay()
        {
            mc.exit();
        }
    }
    
    class MasterClock implements Runnable
    {
        //
        private Ticker;//
        private List waits;
        //
        Boolean running = new Boolean(true);
        //
        public void run
        {
            while(running.BooleanValue())
            {
                //
                if(++Ticker > NextTimeToMoveOnList)
                {
                    Music.nextNote();
                }
                // Looks funny, but is closer to correct practice.
                sleep(0);
            }
        }
        public void startPlay()
        {
            running = new Boolean(true);
        }
        public void stopPlay()
        {
            running = new Boolean(false);
        }
        public void exit()// Not use yet....
    }
    Quote Originally Posted by willemjav View Post
    I haven’t seen any better alternative to my previous loop constructions!
    You have now, though this has considerable detail left out.
    Quote Originally Posted by willemjav View Post
    Maybe because loops form the very hearth of computers and there functioning.
    Basically, this is close to technically correct.
    Quote Originally Posted by willemjav View Post
    Almost everything, concerning a computer, is loop cycle.
    Yes.
    Quote Originally Posted by willemjav View Post
    A program is one the processor cycle is one, events are loops the poor thing has actually noting better to do than spinning its loops.
    Correct.
    Quote Originally Posted by willemjav View Post
    (I know, now that nick is reading carefully - he thinks that I am joking, but I am not, this looping bUssiness is very serious to me so he will surprise me with another mysterious code which should put my thinking into a loop.
    I realize you are not joking, and yes it is funny to me but try not to loop you thinking.
    Quote Originally Posted by willemjav View Post
    (because he is actually the joker of our forum).
    Did you see my post about UFO's in Oklahoma?
    Quote Originally Posted by willemjav View Post
    This new loop waits for the sound tracks to start and is note at the GUI class where buttons etc. are pushed. It sits at the class where all the sounblocks are. The loop happens, again, inside a thread (I start to like threads)
    Just replace the System.out.prints with Music.play(note)
    Quote Originally Posted by willemjav View Post
    The loop will keep the thread busy spinning until the method call of the GUI class turns true. Than the flag gets reset and the important mainSoundblock(1); method starts WITHIN THE THREAD.
    Method call of GUI class is a method call of an instance of MusicPlayer. You have two runs, one is runs music - which runs along a List - iow Plays Music. The other is the system thread with is the gui and so on. You do not program that thread, the window controls take care of that for you. If you want to be able to start and stop your music, you have to have a Thread trapped in a while, which perforce must do a sleep or yield. Everyone codes it like Norm has it. Wait and NotifiyAll have performance issuse that are not important for low data-rate such as midi on one Mac. If that approach makes more sense to you, do it.
    Quote Originally Posted by willemjav View Post
    Consider the working of this method similar to a pin-ball machine. The little ball starts at the very top but eventually will reach the bottom. The if’s, when turn false, will push the ball hard (the esc key was pressed). Each soundblock takes from 20 sec. to several minutes (depending on midi pedals, remember). When reaching the end the thread is over and the cycle/ thread repeats by pushing the start button.
    There are two ways to flip the pinball. One is with a Thread.new() the other is to release a boolean gate on button push, un-gatting a Thread trapped in a do / while. The problem with a do / while is that if the thread is not daemon, we get sluggish exits so what I have decided to do is construct all objects in main() setting daemon == true and calling start on the clock class. GUI class has a reference to the Clock, which does a check on boolean continue running each time around.
    Java Code:
    private void mainSoundblock(int trck)
    {
        if((trck > minValue)&&(trck < maxValue))this.settrackNumb(trck);
        else this.settrackNumb(defalutTrackNumber);
    }
    Giant switches can usually be reduced to a simple variable, check for continue running is moved to MasterClock.
    Quote Originally Posted by willemjav View Post
    By the way PK, when coming out of the loop and NOT coming out of the thread, all the buttons, besides the escape, are turned off (xxx.setEnabled(false) so that no other thread, besides the midipedal and escape, can disturb the pin ball.
    Correct.
    Quote Originally Posted by willemjav View Post
    this funny head appeared by itself?
    Those smileys are actually certain character combinations such as semicolon/right round brace.
    Quote Originally Posted by willemjav View Post
    Location: Spain
    I thought you were in Netherlands.....
    Quote Originally Posted by willemjav View Post
    Yes norm, we might get to the center of this problem (maybe a lack of java imagination of mine). Java does not support multiple inheritance, right. I read some stuff about that, and the point I got out of that all, is that they do not want to turn java into the spaggetti-code mess of C++.
    I would place a joke here but those folks watch too many spaggetti-westerns.
    Quote Originally Posted by willemjav View Post
    I started out with java and do not know any better, good! (I choose for java, because I do not feel any sympathy for the micro-soft (Chicago)software-boys
    Ditto.
    Quote Originally Posted by willemjav View Post
    if you want to know more about that, read Naomi Klein’s latest, The Shock Doctrine (yes, nick I believe we should show our code-biting-juniors about the many hidden background stories of this world).
    Meek, and media-compliant service to normalacy - nothing more. Chicago packs Iron, Naomi doesn't.
    Quote Originally Posted by willemjav View Post
    Okay let’s follow the thread, when the Main class on top of the other classes creates an instance of the second Controler class, that has all the GUI stuff, THERE IS A ONE WAY DIRECTION OF INFORMATION, right.
    GUI -> Controller, clock just slips out of loop if trap variable is false.
    Quote Originally Posted by willemjav View Post
    When the instance of the GUI-class, called count, created at the Main-class (where all the soundblocks are, remember) wants to get data from the GUI-class it gets it by cont.whatever(); If I create a thread at one of the event-notifying methods (of the GUI-class) I WOULD BE GOING INTO THE OPPOSITE DIRECTION.
    Move all driver code to the controller class. Main just construct a few objects and call start on them. That is why Swing has it's own launcher, called javaw.
    Quote Originally Posted by willemjav View Post
    Where is the instance of the Waitloop class created?
    Java Code:
    public static void main
    You do not have a class named
    Java Code:
    Waitloop
    Quote Originally Posted by willemjav View Post
    The return When I Can Execute method would loop/wait until the event occured when you want the mainSoundblock method to be called. This would simplify the design by not requiring the run method to know about setting and clearing flags in the cont class.
    Events, ala AWT / Swing, set variables that are the boolean that Trap the Threads. Wait() and Notifiy are the same thing, except they are written by Engineers for people who think that way.
    Quote Originally Posted by willemjav View Post
    Finally, I have the the program working. I have tested the application many times and everything works just fine. I have to take care of some æsthetical things.... and done. Probably the underlaying mistake of the program is that I did not put the GUI stuff into the top class. I have two waitloops taking care of the GUI management, and one in a new created thread.
    Timer / TimerTask if(nextClock)doSomething();yield();// runs at 1khz
    Java Code:
    do{music}while(run);// wait for start button
    No wait states, just yield or sleep if no work to do....machine is vastly faster than what you think it is.
    Quote Originally Posted by willemjav View Post
    Sure next programming project I should design differently and I will try to get rid of those un-elegant cpu consuming loops.
    Prove they consume cpu cycles needlessly, do not go nuts trying to do that.
    Quote Originally Posted by willemjav View Post
    1) when appending text into a JTextArea, how could I keep the new text on sight at the screen (the new appended text scrolls down and disappears)?
    JTextArea.setText(" ...... ");
    Quote Originally Posted by willemjav View Post
    2) Before going out of the application, at the very last moment, I would like to clean up some things (clossing drivers etc.). I am using the standard
    Java Code:
    window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    put all that in finally of try / catch block, which is entered when do / while is released by setting run boolean to false or better yet per Norm "Use a Window Listener to catch window closing and put a call to your cleanup code there."
    Quote Originally Posted by willemjav View Post
    There is something I am not getting here!
    Vestigages of earlier work, you are moving along.
    Quote Originally Posted by willemjav View Post
    There happens an event in class B (at any time!!!) how this can be noted in A???
    Java Code:
    public static void main(String[] args)
    {
        A a = new A();//
        B b = new B(a);//
        // Or ....
        B b = new B(new A());//
        b.start();
    }
    Quote Originally Posted by willemjav View Post
    At class A I could ask for b.getMidiped() and it will return the correct true or false of the var. But I do not know when that will happen from inside the code of class a so that is why I need a loop to wait this to happen......... Or not???
    One way data-flow, as discussed earlier.
    Java Code:
    public static void main(String[] args)
    {
        do 
        {
            ;//
        }while(boolean run);
    }
    Norm's code is a classic intro to threads, Wait is not a class, has do{}while(); stuffed in somewhere other than where the wait needs to happen.
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  19. #19
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,025
    Rep Power
    8

    Default

    The recursive call should repeat the cycle until,
    window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );


    The waitloop(); // NCR - RECURSIVE CALL???

    be continued!

  20. #20
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,025
    Rep Power
    8

    Default

    "I took your posted code, made it into something that would execute and then modified it to use wait and notify:
    First is your code with some dummy stuff:"

    Okay norm, this code is similar to what I have been doing in my second Gui class, relayed to the first top class that begins a single thread and two loops.

    to be continued

Page 1 of 6 123 ... LastLast

Similar Threads

  1. passing a value from parent thread to child thread
    By sachinj13 in forum Threads and Synchronization
    Replies: 7
    Last Post: 09-07-2008, 09:06 PM
  2. Waiting for a button to be pressed
    By SomeGuyOverThere in forum New To Java
    Replies: 6
    Last Post: 08-21-2008, 09:30 PM
  3. waiting for a file
    By Fleur in forum New To Java
    Replies: 2
    Last Post: 06-23-2008, 08:18 PM
  4. Replies: 0
    Last Post: 01-28-2008, 07:02 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •