Learning Android development.
Code has to wait for few seconds/minutes/hours before going to the next statement in a for Loop.
for( i=0; i<number; i++) {
// Do Something
// Then Wait for x hours, y minutes, and z seconds. Then proceed to next command.
// Do some more things.
} //End for loop.
I searched for this but found many answers like thread.Sleep, Sleep, try{wait(); } Catch{ }, etc...
Also, found out about Handler. Can I use a Handler inside a for loop??
Rather, is there a simple command like wait(x hours, x minutes, x seconds); something like this??
Please help!!
It depends on where do you have the loop. If you run the loop in main thread, you can't "simply insert a delay" into it, because it will block execution, and Java doesn't have anything like C#'s async&await to "easily" solve this. So, the easiest way to do this is: first, move the entire loop to a background thread. Then, you can just use Thread.sleep(…) where you need a delay. But then, if you need to update UI, you can't do this directly from background thread, you will need to use a Handler, call post(Runnable) method (the passed Runnable will run on main thread), and inside that Runnable you must check if the UI is still alive (because user could "close" the application, so your Activity/Fragment/View/whatever can be finished or be in a "bad" state)
In Android there is a class that can do all what you are saying, AsyncTask.
private class YourTaskClassName extends AsyncTask<Void, Integer, Long> {
protected Long doInBackground(Void.. values) {
//Here is where you do the loop
for (int i = 0; i < number; i++) {
...
publishProgress(yourProgress); //Value passed to onProgressUpdate
}
return totalSize; //Value for onPostExecute
}
protected void onProgressUpdate(Integer... progress) {
//Here is what you wanna show while your loop is running in background
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
//Here is what you wanna do when your loop has finished
}
}
You can call it like this new YourTaskClassName().execute();
Thread.sleep(time_in_miliseconds)
looks like the simplest solution. It's a static method, so you need no instances of Thread class.
Wait is a monitor method which means you can call the method from synchronized block or method.
Use sleep for your case.
I've done Android programming in the past but not recently though. I have done lots of Java though and think that I will still be of help.
With respect to the Handler, it appears that you would be able to do this. Having looked at the documentation, http://developer.android.com/reference/android/os/Handler.html#handleMessage(android.os.Message), essentially you're posting messages or runnables from one thread and handling messages in a different thread. Your for-loop won't stop though since you're starting a new thread when using a handler.
When creating a handler, you need to override the handleMessage(Message msg) method if it's a message or post a runnable you're sending as this is the method that's called after a suitable time has ellapsed. To send your message at a specific time or after a delayed amount of time, you have postAtTime, postDelayed, sendMessageAtTime and sendMessageDelayed methods, whichever one is needed.
new Handler() {
public void handleMessage(Message msg) {
// Your code here.
}
}.sendMessageDelayed(yourMessage, theAmountOfTimeInMilles);
Also, after your message is handled, if you want to do any user-interface updating (in other words, changing anything graphical, such as updating a label or changing the background), you need to use the runOnUiThread method, otherwise it will throw an exception:
runOnUiThread(new Runnable() {
public void run() {
// Code including UI code here.
}
});
Related
I have this code sample
public static class BlinkMe extends Thread {
int counter = 0;
protected boolean stop = true;
public void run() {
while (stop) {
counter++;
if (counter % 2 == 0) {
jLabel4.setVisible(true);
jLabel7.setVisible(true);
jLabel8.setVisible(true);
counter = 0;
} else {
jLabel4.setVisible(false);
jLabel7.setVisible(false);
jLabel8.setVisible(false);
if (jButton4.isEnabled() == false) {
stop = false;
jLabel4.setVisible(true);
jLabel7.setVisible(true);
jLabel8.setVisible(true);
if (jButton2.isEnabled() == false) {
stop = true;
jButton2.setEnabled(false);
}
}
}
}
}
}
I need to stop this Thread when I press my Stop Button...
Here's the code I'm using for the Button's function but it is not working. ***The Thread is not working at ll*
Here is the Button's function
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
BlinkMe b=new BlinkMe();
b.stop(); //here I have even used b.interrupt(); but doesn't stop the
}
There are many, many things wrong in this code.
you're accessing Swing components from a background thread. That's forbidden. Only the event dispatch thread is allowed to access Swing components
You're trying to stop() a thread, although this method is deprecaed and should never, ever be used, as the documentation explains
Instead of stopping the actual thread, you create a new instance of that thread class, and call stop() on that new instance.
You "blink" without any delay between the blink.
Your thread uses a stop variable, but this variable is never modified anywhere. Even if it was, it's not volatile, so you have a big chance of not seeing the modification, and thus not stopping the thread.
Read the Swing tutorial abount concurrency. And use a Swing Timer, which is designed to do that kind of thing, safely.
You are creating a new thread in actionPerformed and trying to stop the same, which was not started so far. Try calling stop in actual thread.
The initial value of your stop is "true". This means that when the thread starts, the run method executes but will not execute the while block because the condition will result to false right away.
First, you need to change your while loop into like this:
while(!stop) { /* the rest of your code */ }
Next, you need to create a method in your BlinkMe thread that would allow other objects in your program that would make it stop. The method would look something like this:
public void stopBlinking() {
stop = true;
}
Calling the above method will stop the infinite loop in the run method.
I don't think you will see a blinking effect when you run your program. It is because the loop executes very fast. I suggest you put a Thread.sleep(1000) somewhere in the loop so that there is time to reflect the blink effect visually.
I would like to do something like that:
#Override
protected String doInBackground(Object... params) {
int i = 0;
int max = Integer.MAX_VALUE;
GPSTracker gps = new GPSTracker(context);
do
{
//Something
} while(10 seconds);
return null;
}
How do put a count time in a while statemente. I would like to make this in 10 seconds.
If you're wanting to run a task periodically, use Timer#scheduleAtFixedRate.
To delay execution, you can sleep a thread:
Thread.sleep(timeInMills);
This line may throw a thread exception, and it should never be executed on the main UI thread, as it will cause the app to halt communication with Android, causing a ANR.
To run processes in the background of a single activity, you should spawn a new Thread.
new Thread(){
public void run(){
//Process Stuff
}
}.start();
If you would like to have this section of code run throughout the entire life of your application, including when it is hidden to the user, you should look into running a service for long lived tasks.
A handy alternative to
Thread.sleep(timeInMillis)
is
TimeUnit.SECONDS.sleep(10)
Then the units are more explicit and easier to reason about.
Note that both these methods throw InterruptedException, which you will have to deal with. You can learn more about that here. If, as is often the case, you don't want to use interrupts, and you don't want your code to be cluttered with try/catch blocks, Google Guava's Uninterruptibles can be handy:
Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS);
You can use Thread.sleep(); (Not very clean).
Better use a Handler to do this.
Ex:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// You code here
}
}, 775); // Time in millis
I did it:
long start = System.currentTimeMillis();
long end = start + 60*1000; // 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() < end)
{
// run
}
Thank you for all the answers.
(Problem solved, solution below)
I have 2 classes: Equip and Command. The equip is an equipment that run commands, but I need it to be able to run only 1 command at the same time.
A command is a thread, that executes on the run() function, while Equip is a normal class that don't extend anything.
Currently I have the following setup to run the commands:
Command class:
#Override
public void run() {
boolean execute = equip.queueCommand(this);
if (!execute) {
// if this command is the only one on the queue, execute it, or wait.
esperar();
}
// executes the command.....
equip.executeNextCommand();
}
synchronized public void esperar() {
try {
this.wait();
} catch (Exception ex) {
Log.logErro(ex);
}
}
synchronized public void continue() {
this.notifyAll();
}
Equip class:
public boolean queueCommand(Command cmd) {
// commandQueue is a LinkedList
commandQueue.addLast(cmd);
return (commandQueue.size() == 1);
}
public void executeNextCommand() {
if (commandQueue.size() >= 1) {
Command cmd = commandQueue.pollFirst();
cmd.continue();
}
}
However, this is not working. Basically, the notify() isn't waking the command thread, so it'll never execute.
I searched about the wait and notify protocol, but I couldn't find anything wrong with the code. I also tried calling the wait() directly from the queueCommand() method, but then the execution of the queueCommand stopped, and it also didn't do what it was supposed to do.
Is this approach correct and I'm missing something or this is completely wrong and I should implement a Monitor class to manipulate the concurrent threads?
EDIT: I solved the problem using another completely different approach, using Executors, thanks to #Gray.
Here's the final code, it might help someone someday:
Equip class:
private ExecutorCompletionService commandQueue = new ExecutorCompletionService(Executors.newFixedThreadPool(1));
public void executeCommand(Command cmd, boolean waitCompletion) {
commandQueue.submit(cmd, null);
if (waitCompletion) {
try {
commandQueue.take();
} catch (Exception ex) {
}
}
}
In the Command class I just have a method to encapsulate the equip's execute method.
The boolean waitCompletion is used when I need the result of the command at the same time, and instead of calling a new thread to execute it, I just execute and wait, pretending that it's executing on the same thread. This question contains a good discussion on this matter: When would you call java's thread.run() instead of thread.start()?. And yes, this is a case where it's useful to call .run() instead of .start().
There are a large number of race conditions that exist in your code if Command.run() is called from multiple threads. Unless this is some sort of homework question where you have to implement the code yourself, I would highly recommend using one of the Java Executors which were added in 1.6. In this case the Executors.newSingleThreadExecutor() is what you need to limit the number of running background tasks to 1. This will allow an unlimited number of tasks to be submitted to the ExecutorService, but only one of those tasks will be executing at any one time.
If you need the thread that is submitting the tasks to block when another task is already running then you would use something like the following. This sets up a pool of a maximum of 1 thread and uses a SynchronousQueue which blocks until the worker thread consumes the job:
final ExecutorService executorServer =
new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
But if that was the case then you would just call the task directly inside of a synchronized block and you wouldn't need the ExecutorService.
Lastly, for any new concurrency programmer (of any language) I would recommend that you take the time to read some documentation on the subject. Until you start recognizing the concurrent pitfalls inherent in threading even the simplest set of classes, it will be a frustrating process to get your code to work. Doug Lea's book is one of the bible's on the subject. My apologies if I have underestimated your experience in this area.
I think you should not have "synchronized" on the esperar method. That will block using the object instances as the locking object. Any other thread that attempts to wait will block AT ENTRY TO THE METHOD, not on the wait. So, the notifyAll will release the one thread that got into the method first. Of the remaining callers, only one will proceed with a call to esperar, which will then block on the wait(). Rinse and repeat.
ExectutorService is the way to go. But if you want to do-it-yourself, or need to do something fancier, I offer the following.
I gather than this whole thing is driven by Equip's queueCommand, which might be callled from any thread anywhere at any time. For starters, the two methods in Equip should by synchronized so commandQueue does not get trashed. (You might use ConcurrentLinkedQueue, but be careful with your counts.) Better still, put the code in each method in a block synchronized by queueCommand.
But further, I think your two classes work better combined. Switching Command to a simple Runnable, I'd try something like this:
class Equip {
private Object queueLock = new Object(); // Better than "this".
private LinkedList<Runnable> commandQueue = new LinkedList<Runnable>();
private void run() {
for (;;) {
Runnable cmd = equip.getNextCommand();
if (cmd == null) {
// Nothing to do.
synchronized (queueLock) { queueLock.wait(); }
}
else
cmd.run();
}
}
// Adds commands to run.
public boolean queueCommand( Runnable cmd ) {
synchronized (queueCommand) { commandQueue.addLast( cmd ); }
synchronized (queueLock) {
// Lets "run" know queue has something in it if it
// is in a wait state.
queueLock.notifyAll();
}
}
private Runnable getNextCommand() {
synchronized (queueCommand) { return commandQueue.pollFirst(); }
}
}
You'll need to catch some exceptions, and figure out how to start things up and shut them down, but this should give an idea of how the wait and notify work. (I'd look for some way to know when "run" was not waiting so I could skip synching on queueLock in queueCommand, but walk before you run.)
HI.
I want a function in java that automatically called.
for example wen we use Time class like blew
the actionperformerd() function call every 1second.
Timer time = new Time(10,this);
.
.
.
public void actionperformed()
{
timer.run;
//i want move a pic every 1millisecond.
}
my problem is that Timer class only accept int value and it's minimum
value is 1 second and i want call actionperformed every 1 millisecond.
Java Timer accepts milliseconds in parameters. So you can do
new Timer().schedule(new TimerTask() {
public void run() {
// do stuff
}
}, 1, 1);
But to have real-time functionality with milliseconds precision you may need to switch to C.
Try some classes from java.util.concurrent, and ScheduledThreadPoolExecutor can do the thing you want to do:
public static void main(String[] args) throws Exception {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10);
executor.schedule(new Runnable() {
#Override
public void run() {
// Do something here.
}
}, 1, TimeUnit.MILLISECONDS);
}
BTW, the timer class can't run a job periodically accurately, it can only create one thread to run the task.
You could use a separate Thread
class MyThread extends Thread {
public void run() {
while (!interrupted()) {
try {
// move my object, then sleep for a millisecond
sleep(1);
} catch (InterruptedException e) {
}
}
}
}
However, in practice, you will rarely manage to have you move function called every 1 ms because other threads are also consuming processor time. So you need to take into account the actual time between the end of the previous thread loop and the current time.
I suggest you read lots of tutorials about "Game Loops", you'll learn how to organise the functions moving objects, rendering, ...
This one is an interesting article. Made for Android but can be applied to standard Java.
If this happens to be something graphical be aware that you actually update the screen in the EDT (event dispatch thread). The GUI is not multithreaded.
By hammering your EDT with updates in 1 ms intervals (even worse if you do this per pic) you might in effect make the GUI unusable - it is busy redrawing is stead of responding to user input.
I really don't know whether that effect occurs 1 ms intervals, but the single threaded design of the GUI is something to take into account.
I am trying to program a game in which I have a Table class and each person sitting at the table is a separate thread. The game involves the people passing tokens around and then stopping when the party chime sounds.
how do i program the run() method so that once I start the person threads, they do not die and are alive until the end of the game
One solution that I tried was having a while (true) {} loop in the run() method but that increases my CPU utilization to around 60-70 percent. Is there a better method?
While yes, you need a loop (while is only one way, but it is simplest) you also need to put something inside the loop that waits for things to happen and responds to them. You're aiming to have something like this pseudocode:
loop {
event = WaitForEvent();
RespondToEvent(event);
} until done;
OK, that's the view from 40,000 feet (where everything looks like ants!) but it's still the core of what you want. Oh, and you also need something to fire off the first event that starts the game, obviously.
So, the key then becomes the definition of WaitForEvent(). The classic there is to use a queue to hold the events, and to make blocking reads from the queue so that things wait until something else puts an event in the queue. This is really a Concurrency-101 data-structure, but an ArrayBlockingQueue is already defined correctly and so is what I'd use in my first implementation. You'll probably want to hide its use inside a subclass of Thread, perhaps like this:
public abstract class EventHandlingThread<Event> extends Thread {
private ArrayBlockingQueue<Event> queue = new ArrayBlockingQueue<Event>();
private boolean done;
protected abstract void respondToEvent(Event event);
public final void postEvent(Event event) throws InterruptedException {
queue.put(event);
}
protected final void done() {
done = true;
}
public final void run() {
try {
while (!done) {
respondToEvent(queue.take());
}
} catch (InterruptedException e) {
// Maybe log this, maybe not...
} catch (RuntimeException e) {
// Probably should log this!
}
}
}
Subclass that for each of your tasks and you should be able to get going nicely. The postEvent() method is called by other threads to send messages in, and you call done() on yourself when you've decided enough is enough. You should also make sure that you've always got some event that can be sent in which terminates things so that you can quit the game…
I would look into Locks and Conditions. This way you can write code that waits for a certain condition to happen. This won't take a lot of CPU power and is even much more efficient and better performing than sleeping .
To make a thread run for an infinite time:
final Object obj = new Object();
try {
Thread th = new Thread(new Runnable() {
public void run() {
synchronized(obj) {
try {
System.out.println("Waiting");
obj.wait();
System.out.println("Done waiting");
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
});
th.start();
System.out.println("Waiting to join.");
// Dont notify; but wait for joining. This will ensure that main thread is running always.
th.join();
System.out.println("End of the Program");
} catch(Exception ex) {
ex.printStackTrace();
}
You may add Thread.sleep() with appropriate time to minimize useless loop iterations.
Another solution is using synchronization. While threads are not required to do anything, they enter into a sleeping state on a monitor using the wait() method, and then when the turn comes, required thread is woken up by the notify() method.
Actor model seems suitable for this scenario. Each person sitting on the table and the table itself can be modelled as actors and the event of passing the tokens and starting and stopping of the game can be modelled as messages to be passed between the actors.
As a bonus, by modelling the scenario as actors you get rid of explicit manipulation of threads, synchronization and locking.
On JVM I will prefer using Scala for modelling actors. For Java you can use libraries like Kilim. See this post for a comparison of Actor model related libraries in Java.
One Way is to use while loop but keep a check i.e
while(true){
if(condition!=true){
Thread.sleep(time);
}else{
break;
}
}
This way if your condition says game is not over it will keep person thread at sleep and memory consumption will be very low.
You should test for a condition in the while loop:
while (!gameOver)
{
do_intersting_stuff();
}
Heavy CPU load is typical for busy wait. Is your loop actually just checking a flag over and over, like
while (!gameOver)
{
if (actionNeeded)
{
do_something();
}
}
you might change to another notification system to sleep and wake up, as this just burns CPU time for nothing.