Loop execution speed control - java

Is there a way to control the speed of execution of a loop ?
I have a simulation that runs in a loop of 30000 steps. I want to visualise whats happening in that loop and if possible control the speed of execution while its running. Any ideas how i could do that ?

You could add a sleep to the loop to pause each iteration.
A better question though, is how are you visualizing this? I'm guessing you're watching the text flash by on the console... if that's the case you might want to consider outputting to files rather than the screen. That way you can read through the output at your leisure and you don't have to add artificial slowdowns to the program.
...but if by "visualise" it's an actual GUI thing, then yeah, the sleep might be better.

Put a Thread.sleep() statement inside the loop. Beware though that you have to handle the exception.
for(int i = 0; i < 30000; i++) {
...
try {
Thread.sleep(100);
}
catch(InterruptedException e) {
// do something with e
}
}

you can put inside your loop Thread.sleep(latency); where latency is in millis.

You can try to use 'Thread.sleep()' as the other guys said. But to "know" what happens in the loop I think you'd better debug it.. I think the worst case is to Print everything on the screen (wouldn't be so bad outside a loop, but considering 50+ loops it becomes impracticable.

Related

for loop execute only once

Code only executes once.
Disclaimer: Well aware this is an infinite loop, wrote it this way as part of troubleshooting the problem.
update: There was an exception in my error log that got fixed and the problem is still the same, code only executes once
I tried using the same for loop in the same code for a different task (printing a sentence) and it worked fine, problem must be with my JS code.
for(int i=0; i<i+1;i++) {
((JavascriptExecutor)driver).executeScript("window.open()");
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
driver.get("https://www.google.com");
}
Code is executing only once because of an exception being thrown, OR maybe one or more of the network calls you are making is taking too long that makes you believe that the code is executing only once.
To confirm that the value i + 1, which you are using in the for-loop isn't getting replaced by 1, I ran the following loop on my machine:
for (int i = 0; i < i + 1; i++) {
System.out.println(i);
}
...and it goes on to print numbers starting from 0.
I'm just going to clarify this point as an answer, as I expect the question will be removed.
The for loop isn't your problem. You are writing code which has an exception or is blocking the running thread. If you're using another thread to run this, a lack of an UncaughtExceptionHandler can allow it to skip being logged. Similarly the use of Callable<T> can result in exceptions being swallowed from personal experience (perhaps for the same reason?).
If you are blocking the thread running it, then that thread won't run anything else until the blocking method returns control to the context of where you called it.
Given you said you had cases where the loop "ran once" but still printed after, I'm going to go with it being an exception, and the way that you are running your test is flawed. This can be from an uncountable number of reasons, such as a folly System#exit/Runtime#halt call, threads, using a service to run the tests, or running them in some production environment like a game server or a phone (or... A browser?). For future cases, your questions should ideally be reproducible with nothing other than a main method and the code you provide. If you cannot make such an example, at minimum you should provide how you are testing it.
If you do all of that and still have the issue, I think it will either be obvious to you, or the people reading your question here will have a much easier time answering it for you.

Slow program and reducing performance over time

My program is a Java game which involves taking turns between the user and AI. Therefore after all operations are complete I have a infinite while loop which only breaks after the turn has changed. I only use an infinite loop because I am using a timer and cannot predict when the user ends their turn. But I notice that my program slows down over time to a point where even clicking buttons has no effect. Is it my loop which is causing this? Help would be appreciated.
while(true) {
if(playerTurn % 2 == 1) {
artificialIntelligence();
break;
}
}
If you use an infinite loop(while loop in your case) this operation would be performed continuously; thus slowing your application. Hence, I would suggest breaking the code into two threads.
First thread - Check user-turn event.
Second thread - Do the AI stuff.
As soon as the user event occurs, stop the thread and do what's needed.
This way your code would never be blocked at any point of time; thus resulting in better performance.
Without more code, it is hard to determine what is the real cause of the problem. However, one suspect may be that you're holding on to object references and they're not being reclaimed by garbage collection. Try using a java profiler, it can help you to pin point where exactly the issue may arise.

Better way to implement empty while loop to hold control

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.

Does suspending thread make any changes?

I have a simple question
does it make any difference to try suspending a thread(in my situation)?
my thread is just an image rotator (my minSDK is 8 so must use matrix, not animation)
i have just asked a question about how to suspend a thread. everyone offered using:
while(isPaused){
try {Thread.sleep(25);}catch(...){...}
}
and my code is like this :
while(true){
//rotate image 15 deg
try {Thread.sleep(25);}catch(...){...}
}
they offer to use the first while inside the while(true)
does it make much difference ?
(I don't have to stop the thread. I can just make the rotating image invisible)
Simpler :
Does it make difference to use this to pause a thread :
while(true){
while(isPaused){
try {Thread.sleep(25);}catch(...){...}
}
//rotate image 15 deg
try {Thread.sleep(25);}catch(...){...}
}
or there isn't any problem leaving the code to rotate an invisible image ?
Edit: considering this is for a custom loading indicator, please don't use a thread. That is overkill for such a simple thing. Have a look at this answer on how to create custom loading indicators using animations.
https://stackoverflow.com/a/8129496/2910492
This has entirely to do with your application. Some more information would be useful, but in general, it seems unnatural to have an image rotating while things are supposed to be paused. Even if the image is invisible, it would (presumably) come back in a different orientation than it was when paused.
Also, the computer's resources must be consumed to continue rotating the image, which is probably not desirable. So I'd revise your code to keep things from executing while paused as such:
while(true){
if(!isPaused){
//rotation code
}
try {Thread.sleep(25);}catch(...){...}
}
Doing things this way eliminates some re-use of code. When you have a way to eliminate code and not repeat yourself, it is almost always a good idea to employ it. Repeated code means repeated errors and makes more work for you when you need to change something. If you have to copy and paste something, stop and do some soul-searching: there is most likely a better way.
You should use the "condition" instead of "true" in your while loop. That condition should be useful to complete the working of the thread.
For e.g. you may not want to make the thread orphan and keep on running even if application gets ended. So in onDestroy you can make that conditional flag false and your while loop gets failed hence thread completes it's task.

Using methods inside loops, Java and Android

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;
}

Categories

Resources