Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Wait - Hold function

 
Gabriel Collet
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi.
I need to have my program wait for a couple of seconds before doing the next instruction or wait for an event to happen. How can I do it?

Thanks a lot for your help
 
Andy Robinson
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
j2me does have a Timer function that could be of use to you.
Check out java.util.Timer and .TimerTask, these let you create a Timer and schedule tasks to happen after a certain number of milliseconds.
 
vishwas bhatt
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Andy,

can we do this without using timer.I mean we have two thread one is a main thread and another one which handels enents. can we do wait()/notify() between these two thread. if yes please tell me how?

Thanks
Waiting for reply.
 
Andy Robinson
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well I don't think j2me is any different from normal java when it come to threads so you should be able to use wait() and notify().
So if you want to make the main thread wait while the other thread does something your code would go something like this -
Main thread
try{
wait();
}catch (InterruptedException e) {}
}

Second thread
//some action code
notify();
or, if you have more than one thread waiting
notifyAll();

Or you could use the System.currentTimeMillis() method to time exactly when events happen, although this harder to do.
Hope that helps.
 
Michael Yuan
author
Ranch Hand
Posts: 1427
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can share a state variable between the two threads. Thread A writes to that variable when its state changes. Thread B checks the variable value in a loop and perform some action once it detects a change
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic