I have a series of IF statements in order of execution, my dilemma is if one of the IF statements is entered I would like the calling method to wait till the called function is finished. The thing is my called function is recursive so I have no idea when it's going to end. Here's the calling method's code.
if(log.isChecked())
{
runlog(sdPath.getAbsolutePath());
}
if(tmp.isChecked())
{
runtmp(sdPath.getAbsolutePath());
}
if(txt.isChecked())
{
runtxt(sdPath.getAbsolutePath());
}
if(bf.isChecked())
{
runbf(sdPath.getAbsolutePath());
}
if(ed.isChecked())
{
runed(sdPath.getAbsolutePath());
}
If log.isChecked() is entered, I would like the calling function(the code I've shown here, that function) to wait till it checks the next condition which is tmp.isChecked()
As I mentioned before ALL the called functions runlog, runtmp, runtxt, runbf, runed are recursive. How do I achieve what I want?
I think recursion can is best explained with the movie "Inception". You have 3 things you want to do.
Go to sleep.
Dream.
Wake up and eat a bowl of cereal.
Imagine you are dreaming and then have a dream within that dream. You now can't wake up and eat until you exit out of the deeper dream and finish the current dream.
That is basically what is happening in your example except instead of dreaming you ran the first if and you can't exit it until it reaches its return condition then you get to wake up and eat (enter the second if).
This should happen by default. The nested functions being recursive makes no difference here.
Each if block will only be executed after one the previous one has completed unless your nested functions are starting threads or something of that sort.
Related
class Test {
int i=0;
void method2() {
if(i==6) return;
System.out.print("before");
i++;
method2();
System.out.println("after"):
}
}
If I call method2() from another class then I want to know how the program will flow here or why the output that's executed.
In depth knowledge of recursion can be found here
https://en.m.wikipedia.org/wiki/Recursion_(computer_science)
As far as your program is concerned it will stop when i=6
Otherwise it will keep on printing before.
This is because in programming the flow of control is never skipped it follows the flow of control but it is not that it leaves the rest statement so whenever a new call to a function is generated the previous status of the functioning is being pushed in stack one by one and so the stack is kept on increasing and when finally the end condition is reached it pops all function calls one by one from the activation record and does the required processing is done and thus recursion works.
It takes help of a stack for doing operations.
The program flow always follows it's order wheather you call it from anywhere.
So the program flow remains same.
You will easily understand the working if you run it and add some more print statement with also the values of i.
Here is a simplified version of my code. function1() has to check something on the internet. It has to do it in the background of the app(I cannot change that), which allows the rest of the code to run while it checks the internet. This function can take several seconds to complete. I cannot put the log at the end of function 1 because it needs to run whether function1 is successful or not, but only after it is done trying. How can I achieve this without using a timer?
if (condition) {
if (condition2) {
function1();
}
Log.i("Info", "This should not appear until function1 completes or fails");
}
Don't constantly check; this is called busy waiting and is inefficient, especially on mobile (since the device can't go into low-power mode). Instead, use an AsyncCallback to run your function1 and put the log message in the callback.
I want to start a loop coded in C++ that is run untill I ask it (from Java) to stop.
IE:
(in c++)
void loop(){
while(!stop){
// do something
}
}
in Java:
MyLib.INSTANCE.loop();
then call something like :
MyLib.INSTANCE.stop = true;
Is it possible ?
While you can access a shared library's globals (NativeLibrary.getGlobalVariableAddress()), it's preferable to define a dedicated function which does what you want (i.e. MyLib.stop()).
You also need to take care that your code is multi-thread aware, so that the compiler doesn't think your loop's stop cannot be changed and thus optimizes it away. You also need to ensure that your loop doesn't monopolize the CPU; it needs to yield from time to time if you want your "stop" code to be able to run.
I am playing audio in background and I want the control of program to stay stand still till the audio playing is over for that I am using empty while loop as follows
while(isPlaying==true){};
mediaPlayer.stop();
as you can see while loop holds program control till audio is playing and after that next instruction is executed. This is working fine but I came to know that this is not a proper way to do this empty-while is expensive I am searching for alternative. Please Help.
Assuming your program is in Java (...why did you give it three language tags?) You have a few options. You could use a proper synchronization event, e.g.:
// fields
Object playerStopEvent = new Object();
boolean isPlaying;
// in your media player, when playback is complete:
synchronized (playerStopEvent) {
isPlaying = false;
playerStopEvent.notifyAll();
}
// elsewhere, when waiting for playback to complete:
synchronized (playerStopEvent) {
while (isPlaying) {
try {
playerStopEvent.wait();
} catch (InterruptedException x) {
// abort or ignore, up to you
}
}
}
mediaPlayer.stop();
See the official tutorial on Guarded Blocks for more examples.
You could also just have mediaPlayer call some callback when it is finished, and e.g. disable GUI components when you start playing and re-enable them when the finished callback is called (you could also use an event listener approach here).
Without more info, I recommend the latter, as it won't prevent you from doing other unrelated things (or keep your program from responding at all) while the player is playing, but the former may be more appropriate depending on your situation.
If it's in C or C++ the concept is the same. Use whatever equivalent of condition variables / events you have for the first option, or whatever equivalent of callbacks / listeners / signals+slots you have for the second.
well, in my humble opinion, it's better to use another implementation..
try to use thread so that it won't hang your program in there (it's a background audio afterall; you might want to do something else while the audio is playing)..
try to check this page out..
First thing is that you don't have to compare 2 Boolean fields that you have done in your code...
while(isPlaying==true){};
you can do so like..
while(isPlaying){};
and, now that you have told that you are using java, you can try this...
while(isPlaying){
Thread.sleep(1);
};
You may consider a sleep(time in milliseconds ). This will allow your thread executing while loop to sleep for specified milliseconds and then check the condition again.
while(isPlaying==true)
{
Thread.currentThread().sleep(1000); // sleep for 1 sec
};
This once is quick but the better way is to use some wait() and notify() mechanism as suggested by #JasonC in his answer.
You really don't need the {} in your empty while loop.
while(isPlaying); would suffice.
Also, as others have already suggested, consider using a delay inside your loop, i.e.
Thread.sleep(100); // sleeps for 1/10 of a seconds in Java
Or
delay(100); // leeps for 1/10 of a seconds in Java
The simple way is that put sleep(1) in while loop. And cpu usage won't take more.
I'm working on a Java class in an Android project that summarizes array entries saved in previous classes, with each entry itself being an array with multiple elements.
I've have created methods to move forwards and backwards through the entries, but given there can be over 100 entries I would like to create another method that cycles through them instead of pressing the "Next" button over and over again.
Is there a way to do this?
I've found that loops will only show the last entry, but below is the best example I can think of, of what I need.
for (int i = Selection; i<=Qty; i++){
Num.setText(Integer.toString(i));
loadNext();
try{
Thread.sleep(1500);
}catch(InterruptedException e){}
if (Brk=true){
break;
}
}
The solution that would be closest to your original answer would be to create a background thread that does the loop, loading each item inside an Activity.runOnUiThread(). You can also do a similar thing with AsyncTask and progress updates. See this article for more information on both of these:
http://developer.android.com/resources/articles/painless-threading.html
However, a better solution is to not have a loop at all - just have a timer, and increment your loop variable each time the timer runs.
It may work. However, it will cause your UI to freeze during each time you call the sleep method. In general, when you are dealing with UI stuff, never use Thread class. Instead, use the Handler class. There are a lot of documentation but if, after you have search exhaustively, you can't find a good example just let me know.
Your break condition seems wrong, and causes the loop breaks at the first iteration:
if (Brk=true){
break;
}
Brk=true is an assigment exception, not a comparation exception. It will return always true. The expresion should be Brk==trueto check if the variable value is true. But again, it is a boolean variable, so you don't need to compare, but just reference it at the if statement:
if (Brk){
break;
}