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.
Related
I'm using 3rd party which drawing to a view something.
I got the process threads list and i found the thread they are using to draw their stuff in.
I want to add my drawing code in this thread - meaning when they are finishing drawing their stuff in the thread then my code will run and then the thread will end (or whatever happens with it).
I tried to do my drawing code in different thread and UI Thread but I can see that my drawing is running after the 3rd party when we change the camera position.
Is it possible to inject some code into another thread? btw, I have only their Thread object in my hand which i got from running over all the threads list.
If not, other solution will be fine also (if there is)
-- EDIT --
Tried to suspend their thread, draw my stuff, and resume, but it is crashing - guess due to those are deprecated functions
Purely theoretical stuff ahead:
Check if they support drawing to backbuffer (not screen) -- OR -- try to redirect drawing to a backbuffer(framebuffer). Do your drawing in the backbuffer too. Manually switch backbuffer (actually back framebuffer) with front framebuffer.
They are most probably doing their drawing in a loop. The onDraw may be event triggered or it just tries to provide as much fps as it can. But if you synchronize the access to your backbuffer, you may force their draw thread to wait exactly for the time you do your drawing and the swap of buffers. You need to initially sync your procedure with theirs (probably by painfully testing that your code gets to run from time to time, and drawing is not blocked). And you must remember that if this work, the synchronization will mean that their thread will wait on their N loop for the end of your N-1 loop at exactly the first operation working with the backbuffer.
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 have just found the code to a small WAV player.
It works well but when clicking the "Pause" and "Stop" buttons there's like a 2 seconds delay which makes the app look really unprofessional. I have no idea what is causing this but I'd really like to have it fixed, could anyone inspect the code and tell me where it comes from? Thanks!
I wrote this sample for a time and don't remember very well.
In my opinion the latency comes mainly from the update frame functions. In the class VisualPlayer, UI are update by a timer which pick up the current values from the thread. It's not very efficient but faster for write this sample.
The best way to update UI is implementing a Runnable class and call it with SwingUtilities.invokeLater().
Also have you try to reduce read buffer size ?
I'm still working on moving my android app over to OpenGL and i'm once again having an issue.
I have gotten to the point where everything FUNCTIONS, the only problem is that the animation seems a little juddery.
I'm monitoring the frame rates and seeing that the drawing thread isn't slowing down, but every once in a while, the main loop slows a bit and I suspect I'm having a problem I was worried about.
The way the app works is that as new objects (say for instance, enemies) are created, 2 objects are actually created. The first one is created and mapped in the main thread, and then in it's constructor, it creates a mesh object which is then added to a group to be drawn continuously by the renderer.
Every time an attribute for the object is changed, (such as its coordinates) The object relays the necessary command to its mesh counterpart (in this example to translate the mesh.)
It was suggested that this was thread safe communication, but i'm having my doubts. I also notice a greater amount of frame skip when new objects are created, I can fix this somewhat by reusing the same mesh object for identical Game objects, but I don't believe this will fix everything by itself.
Can you think of a way to make this more efficient and thread-safe?
Another possible solution: The game logic does not HAVE to go at full speed (realtime) I have it actually set up so that no updates are made untill 33 millis pass. So obviously, I should have plenty of time between frames to draw, can I set it up so that draw is only called on command in the thread (after the game logic has been updated)?
It looks like you need something like a ScheduledThreadPoolExecutor.
With one of these you could put your renderer on a schedule so it executes at 30fps leaving your main/control thread to do whatever it needs to do to the object map between frames.
I don't think you need any wait/notify interlocking as all you really need is to block access to the map while the renderer is walking it. To do this you just need to make the map synchronized. As this will only happen once every 1/30th of a second you are certainly not introducing a significant overhead.
Your main aim should be to put as little unnecessary load on the CPU as possible, this is the key to smooth multithread work. Try to spend as much time as possible either sleeping or blocked.
Added
I subtract the time it took to loop from 33ms, and use the result to specify the length of sleep().
I wonder if that may be part of your issue. On a Windows machine you often get a 15ms resolution on the currentTimeMillis so your sleeps may end up hardly sleeping at all. It may be worth experimenting with a ScheduledThreadPoolExecutor just to see if it improves your timing. ... oops ... this is Android isn't it. Still ... it may be worth a try.
I'm writing a game in Java. And, oh wonder, i have performance issues. I benchmarked the paint itself - 1000 cycles in 3 ms tops. The game logic is even below that. So far, so good. But i still encounter an annoying lag: When scrolling, when zooming, when clicking. The problems get worse when i zoom in and more objects are placed. But still - even when I loop the painting a 1000 times the lags stays more or less the same, so that cant be it.
I tried putting the loop in a task - still the same. I tried pausing the task in between paints - still the same.
Animations run as smooth as silk (since the framerate is stable and high, that makes sense). So how on earth do i organize the inputs in an orderly fashion? Put them all in a seperate thread?
Any input would and will be greatly appreciated!
It sounds like you're using listener callbacks directly on the Swing Event Dispatch Thread, where the UI updates are being done. You should use a command queue, and put events on the queue when a callback is invoked, with the nature of the command, then you use this in the main game update loop that has nothing to do with the EDT.