Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Java ME - 04 - Timer, Tasks and Threads


Published on

Most mobile applications will have to use asynchronous processing — for running the game loop or for connecting your MIDlet to the Internet. This module is a repetition of the basic thread concepts that you will need for your mobile applications. It also contains details of how to use the Timer to generate regular call-backs. In the first challenge, you will write a small alarm clock based on the high level user interface. The second challenge is about drawing a ball that bounces around on the screen using the low level graphics API.


* Timer
* Scheduling
* Threads
* Runnable vs. Thread

Published in: Technology
  • Hi there! Get Your Professional Job-Winning Resume Here - Check our website!
    Are you sure you want to  Yes  No
    Your message goes here

Java ME - 04 - Timer, Tasks and Threads

  1. 1. Java™ Platform, Micro Edition<br />Part 4 – Timer, Tasks and Threads<br />v3.0 – 02 April 2009<br />1<br />Andreas Jakl, 2009<br />
  2. 2. Disclaimer<br />These slides are provided free of charge at and are used during Java ME courses at the University of Applied Sciences in Hagenberg, Austria at the Mobile Computing department ( )<br />Respecting the copyright laws, you are allowed to use them:<br />for your own, personal, non-commercial use<br />in the academic environment<br />In all other cases (e.g. for commercial training), please contact<br />The correctness of the contents of these materials cannot be guaranteed. Andreas Jakl is not liable for incorrect information or damage that may arise from using the materials.<br />This document contains copyright materials which are proprietary to Sun or various mobile device manufacturers, including Nokia, SonyEricsson and Motorola. Sun, Sun Microsystems, the Sun Logo and the Java™ Platform, Micro Edition are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. <br />Andreas Jakl, 2009<br />2<br />
  3. 3. Contents<br />Timer<br />Threads<br />Andreas Jakl, 2009<br />3<br />
  4. 4. Timer<br />Execute tasks at a specified time<br />Andreas Jakl, 2009<br />4<br />
  5. 5. Timer<br />Asynchronous execution of a task <br />after a specified amount of time (nonrecurring) or …<br />in certain intervals (periodic)<br />Two classes are involved:<br />Andreas Jakl, 2009<br />5<br />Timer<br />Scheduling when a task will occur<br />TimerTask<br />Performing a task<br />
  6. 6. Nonrecurring Events<br />Andreas Jakl, 2009<br />6<br />Start timer<br />void schedule(TimerTask task, long delay)<br />… 1500 ms …<br /><br />void schedule(TimerTask task, Date time)<br />16.11.2007, 10:27:31<br /><br />Time<br />
  7. 7. Applications<br />After x milliseconds<br />Delayed start of an asynchronous processe.g. MIDletstartup: give VM time to draw the splash screen before loading and initializing the game<br />Countdown<br />At a specified point in time<br />Alarm clock<br />Andreas Jakl, 2009<br />7<br />
  8. 8. Periodic Tasks<br />Andreas Jakl, 2009<br />8<br />voidscheduleAtFixedRate([…], longperiod)<br />300 ms<br />300 ms<br />300 ms<br />300 ms<br />300 ms<br />delay<br />Time<br />delay<br />task<br />task<br />task<br />task<br />task<br />t2<br />Thread<br />350 ms<br />300 ms<br />300 ms<br />300 ms<br />voidschedule([…], longperiod)<br />delay<br />delay<br />300 ms<br />300 ms<br />300 ms<br />300 ms<br />Time<br />task<br />task<br />task<br />task<br />task<br />t2<br />Thread<br />300 ms<br />350 ms<br />250 ms<br />300 ms<br />
  9. 9. Fixed Delay<br />If consistency is more important than accuracy<br />Execution is delayed (e.g. by garbage collection):<br />Only one execution is delayed<br />After this, the constant interval is kept up again<br />Suitable for:<br />Animations: shouldn’t suddenly move faster<br />Unsuitable for:<br />Clock: Inaccuracies would accumulate<br />Andreas Jakl, 2009<br />9<br />voidschedule([…], longperiod)<br />delay<br />delay<br />300 ms<br />300 ms<br />300 ms<br />300 ms<br />Time<br />task<br />task<br />task<br />task<br />task<br />t2<br />Thread<br />
  10. 10. Fixed Rate<br />When accuracy is more important<br />Execution is delayed (e.g. by garbage collection):<br />Two or more subsequent executions are scheduled at shorter intervals to “catch up”<br />None of the events will be dropped<br />(Un)suitable:<br />Inverse to fixed delay<br />Andreas Jakl, 2009<br />10<br />voidscheduleAtFixedRate([…], longperiod)<br />300 ms<br />300 ms<br />300 ms<br />300 ms<br />300 ms<br />delay<br />Time<br />delay<br />task<br />task<br />task<br />task<br />task<br />t2<br />Thread<br />
  11. 11. Combination<br />Andreas Jakl, 2009<br />11<br />When to start first task?<br />Execute 1st task after x ms<br />Execute 1st task at specified time<br />1: One Time<br />2: Fixed Delay<br />3: Fixed Rate<br />4: One Time<br />5: Fixed Delay<br />6: Fixed Rate<br />1: schedule(TimerTask task, long delay)<br />2: schedule(TimerTask task, long delay, long period)<br />3: scheduleAtFixedRate(TimerTask task, long delay, long period)<br />4: schedule(TimerTask task, Date time)<br />5: schedule(TimerTask task, Date firstTime, long period)<br />6: scheduleAtFixedRate(TimerTask task, Date firstTime, long period)<br />
  12. 12. TimerTask<br />Create your own class derived from TimerTask<br />Pass an instance of it to the Timer-object<br />Calls run() of your TimerTask-class at the specified time<br /> implement the abstract run()-method!<br />Andreas Jakl, 2009<br />12<br />
  13. 13. Example<br />Andreas Jakl, 2009<br />13<br />// Allocate a timer<br />Timertm = newTimer();<br />// Schedule thetimerwithappropriateschedulingoption, eg. in 1000 milliseconds<br />tm.schedule(newTodoTask(), 1000);<br />[…]<br />private classTodoTaskextendsTimerTask<br />{<br />public final voidrun()<br /> {<br /> // Do something …<br /> }<br />}<br />
  14. 14. Threads<br />Control an asynchronoustask<br />Andreas Jakl, 2009<br />14<br />
  15. 15. Why Threads?<br />Examples:<br />Game loop, has to be executed all the time, as often as possible<br />To make animations as smooth as possible.<br />A fixed delay timer would result in a fixed amount of frames per second and not utilize better hardware<br />Animated progress bar while loading or processing<br />Connect through HTTP / Sockets<br />Connection process can be stopped by JVM to display a security warning<br />Without threads: app. couldn’t process key press anymore, would lock<br />Andreas Jakl, 2009<br />15<br />
  16. 16. Possibilities<br />Andreas Jakl, 2009<br />16<br />1. Derive your own object from Thread,implement run()<br />2. Extra (2nd) object implements the Runnable-interface, start through Thread-object.<br />Thread<br />Thread<br />Interface<br />Runnable<br />run()<br />Interface<br />Runnable<br />run()<br />MyThread t = new MyThread();t.start()<br />DoSomething doIt = new DoSomething();Thread t = new Thread( doIt );t.start();<br />
  17. 17. Example – Thread-Object<br />Andreas Jakl, 2009<br />17<br />DoAnotherThingdoIt = new DoAnotherThing();<br />doIt.start();<br />// …<br />public class DoAnotherThingextends Thread {<br />publicvoid run() {<br />// Here is where you do something<br /> // Executed within its own thread!<br /> }<br />}<br />
  18. 18. Example – Runnable-Object<br />Andreas Jakl, 2009<br />18<br />DoSomethingdoIt = newDoSomething();Thread t = new Thread( doIt );t.start();<br />publicclassDoSomethingimplementsRunnable{ private booleanquit = false;<br />publicvoidrun() {while( !quit ) {// do something, e.g. processthe<br /> // nextframe in a game } } publicvoidquit() {quit = true; }}<br />
  19. 19. Differences: Runnable / Thread?<br />Almost identical.<br />Advantages of the Runnable-variant (interface):<br />Can be implemented by existing class (no multiple inheritance in Java (extend Thread)!)<br />Therefore, saves an additional class<br />Andreas Jakl, 2009<br />19<br />
  20. 20. Structure<br />run()-method can be used for single action<br />Once run() method is left, thread stops and is cleaned up<br />Commonly, run()repeats an action until some condition is satisfied (e.g., in a game loop)<br />Implement infinite loop in run()<br />To exit the loop and stop the thread:<br />Repeatedly query boolean status variable<br />If set to true through any function  break loop and therefore leave run()-method, thread is stopped<br />Andreas Jakl, 2009<br />20<br />
  21. 21. Additional Possibilities<br />For more complex threading tasks, use:<br />Synchronisation, Wait, … <br />More information:<br /><br />Andreas Jakl, 2009<br />21<br />
  22. 22. … let’s move on to the challenges!<br />Interactive<br />Andreas Jakl, 2009<br />22<br />