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:
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.
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();
}
this funny head appeared by itself?
Quote:
Originally Posted by
willemjav
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. ( ! )
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:
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
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)
*/
do{}while(); is not wait() / notifiy()
Quote:
Originally Posted by
willemjav
(Or how to get into one and, most importantly, how to get out of a one.)
Really simple: 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
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
Maybe because loops form the very hearth of computers and there functioning.
Basically, this is close to technically correct.
Quote:
Originally Posted by
willemjav
Almost everything, concerning a computer, is loop cycle.
Yes.
Quote:
Originally Posted by
willemjav
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
(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
(because he is actually the joker of our forum).
Did you see my post about UFO's in Oklahoma?
Quote:
Originally Posted by
willemjav
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
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
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.
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
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
this funny head appeared by itself?
Those smileys are actually certain character combinations such as semicolon/right round brace.
Quote:
Originally Posted by
willemjav
Location: Spain
I thought you were in Netherlands.....
Quote:
Originally Posted by
willemjav
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
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
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
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
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
Where is the instance of the Waitloop class created?
Code:
public static void main
You do not have a class named Quote:
Originally Posted by
willemjav
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
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
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
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
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
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
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
There is something I am not getting here!
Vestigages of earlier work, you are moving along.
Quote:
Originally Posted by
willemjav
There happens an event in class B (at any time!!!) how this can be noted in A???
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
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.
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.