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

Weitere ähnliche Inhalte

Andere mochten auch

Paradise Lost
Paradise LostParadise Lost
Paradise Lost
janewoo
 

Andere mochten auch (7)

Java ME - 03 - Low Level Graphics E
Java ME - 03 - Low Level Graphics EJava ME - 03 - Low Level Graphics E
Java ME - 03 - Low Level Graphics E
 
Java ME - 07 - Generic Connection Framework, HTTP and Sockets
Java ME - 07 - Generic Connection Framework, HTTP and SocketsJava ME - 07 - Generic Connection Framework, HTTP and Sockets
Java ME - 07 - Generic Connection Framework, HTTP and Sockets
 
Java ME - 08 - Mobile 3D Graphics
Java ME - 08 - Mobile 3D GraphicsJava ME - 08 - Mobile 3D Graphics
Java ME - 08 - Mobile 3D Graphics
 
Java ME - 05 - Game API
Java ME - 05 - Game APIJava ME - 05 - Game API
Java ME - 05 - Game API
 
Java ME - 01 - Overview
Java ME - 01 - OverviewJava ME - 01 - Overview
Java ME - 01 - Overview
 
Java ME - 02 - High Level UI
Java ME - 02 - High Level UIJava ME - 02 - High Level UI
Java ME - 02 - High Level UI
 
Paradise Lost
Paradise LostParadise Lost
Paradise Lost
 

Ähnlich wie Java ME - 04 - Timer, Tasks and Threads

REAL TIME OPERATING SYSTEM
REAL TIME OPERATING SYSTEMREAL TIME OPERATING SYSTEM
REAL TIME OPERATING SYSTEM
prakrutijsh
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS Multithreading
Richa Jain
 
The Pillars Of Concurrency
The Pillars Of ConcurrencyThe Pillars Of Concurrency
The Pillars Of Concurrency
aviade
 
Threaded Programming
Threaded ProgrammingThreaded Programming
Threaded Programming
Sri Prasanna
 

Ähnlich wie Java ME - 04 - Timer, Tasks and Threads (20)

Symbian OS - Active Objects
Symbian OS - Active ObjectsSymbian OS - Active Objects
Symbian OS - Active Objects
 
Symbian OS - Memory Management
Symbian OS - Memory ManagementSymbian OS - Memory Management
Symbian OS - Memory Management
 
Is your profiler speaking the same language as you? -- Docklands JUG
Is your profiler speaking the same language as you? -- Docklands JUGIs your profiler speaking the same language as you? -- Docklands JUG
Is your profiler speaking the same language as you? -- Docklands JUG
 
Microservices with Micronaut
Microservices with MicronautMicroservices with Micronaut
Microservices with Micronaut
 
REAL TIME OPERATING SYSTEM
REAL TIME OPERATING SYSTEMREAL TIME OPERATING SYSTEM
REAL TIME OPERATING SYSTEM
 
Microservices with Micronaut
Microservices with MicronautMicroservices with Micronaut
Microservices with Micronaut
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS Multithreading
 
Developing Async Sense
Developing Async SenseDeveloping Async Sense
Developing Async Sense
 
Core Java Programming Language (JSE) : Chapter XII - Threads
Core Java Programming Language (JSE) : Chapter XII -  ThreadsCore Java Programming Language (JSE) : Chapter XII -  Threads
Core Java Programming Language (JSE) : Chapter XII - Threads
 
Object - Based Programming
Object - Based ProgrammingObject - Based Programming
Object - Based Programming
 
JavaFX Pitfalls
JavaFX PitfallsJavaFX Pitfalls
JavaFX Pitfalls
 
Taking advantage of the Amazon Web Services (AWS) Family
Taking advantage of the Amazon Web Services (AWS) FamilyTaking advantage of the Amazon Web Services (AWS) Family
Taking advantage of the Amazon Web Services (AWS) Family
 
The Pillars Of Concurrency
The Pillars Of ConcurrencyThe Pillars Of Concurrency
The Pillars Of Concurrency
 
ADVANCED WORKSHOP IN MATLAB
ADVANCED WORKSHOP IN MATLABADVANCED WORKSHOP IN MATLAB
ADVANCED WORKSHOP IN MATLAB
 
Tech talk
Tech talkTech talk
Tech talk
 
Computer Networks Omnet
Computer Networks OmnetComputer Networks Omnet
Computer Networks Omnet
 
Javascript Stacktrace Ignite
Javascript Stacktrace IgniteJavascript Stacktrace Ignite
Javascript Stacktrace Ignite
 
Threaded Programming
Threaded ProgrammingThreaded Programming
Threaded Programming
 
03 objective-c session 3
03  objective-c session 303  objective-c session 3
03 objective-c session 3
 

Mehr von Andreas Jakl

Mehr von Andreas Jakl (20)

Create Engaging Healthcare Experiences with Augmented Reality
Create Engaging Healthcare Experiences with Augmented RealityCreate Engaging Healthcare Experiences with Augmented Reality
Create Engaging Healthcare Experiences with Augmented Reality
 
AR / VR Interaction Development with Unity
AR / VR Interaction Development with UnityAR / VR Interaction Development with Unity
AR / VR Interaction Development with Unity
 
Android Development with Kotlin, Part 3 - Code and App Management
Android Development with Kotlin, Part 3 - Code and App ManagementAndroid Development with Kotlin, Part 3 - Code and App Management
Android Development with Kotlin, Part 3 - Code and App Management
 
Android Development with Kotlin, Part 2 - Internet Services and JSON
Android Development with Kotlin, Part 2 - Internet Services and JSONAndroid Development with Kotlin, Part 2 - Internet Services and JSON
Android Development with Kotlin, Part 2 - Internet Services and JSON
 
Android Development with Kotlin, Part 1 - Introduction
Android Development with Kotlin, Part 1 - IntroductionAndroid Development with Kotlin, Part 1 - Introduction
Android Development with Kotlin, Part 1 - Introduction
 
Android and NFC / NDEF (with Kotlin)
Android and NFC / NDEF (with Kotlin)Android and NFC / NDEF (with Kotlin)
Android and NFC / NDEF (with Kotlin)
 
Basics of Web Technologies
Basics of Web TechnologiesBasics of Web Technologies
Basics of Web Technologies
 
Bluetooth Beacons - Bluetooth 5, iBeacon, Eddystone, Arduino, Windows 10 & More
Bluetooth Beacons - Bluetooth 5, iBeacon, Eddystone, Arduino, Windows 10 & MoreBluetooth Beacons - Bluetooth 5, iBeacon, Eddystone, Arduino, Windows 10 & More
Bluetooth Beacons - Bluetooth 5, iBeacon, Eddystone, Arduino, Windows 10 & More
 
Which new scenarios are enabled by Windows 10 for NFC, Bluetooth LE & Beacons?
Which new scenarios are enabled by Windows 10 for NFC, Bluetooth LE & Beacons?Which new scenarios are enabled by Windows 10 for NFC, Bluetooth LE & Beacons?
Which new scenarios are enabled by Windows 10 for NFC, Bluetooth LE & Beacons?
 
Mobile Test Automation
Mobile Test AutomationMobile Test Automation
Mobile Test Automation
 
Qt App Development - Cross-Platform Development for Android, iOS, Windows Pho...
Qt App Development - Cross-Platform Development for Android, iOS, Windows Pho...Qt App Development - Cross-Platform Development for Android, iOS, Windows Pho...
Qt App Development - Cross-Platform Development for Android, iOS, Windows Pho...
 
WinJS, Apache Cordova & NFC - HTML5 apps for Android and Windows Phone
WinJS, Apache Cordova & NFC - HTML5 apps for Android and Windows PhoneWinJS, Apache Cordova & NFC - HTML5 apps for Android and Windows Phone
WinJS, Apache Cordova & NFC - HTML5 apps for Android and Windows Phone
 
Nokia New Asha Platform Developer Training
Nokia New Asha Platform Developer TrainingNokia New Asha Platform Developer Training
Nokia New Asha Platform Developer Training
 
Windows Phone 8 NFC Quickstart
Windows Phone 8 NFC QuickstartWindows Phone 8 NFC Quickstart
Windows Phone 8 NFC Quickstart
 
Windows (Phone) 8 NFC App Scenarios
Windows (Phone) 8 NFC App ScenariosWindows (Phone) 8 NFC App Scenarios
Windows (Phone) 8 NFC App Scenarios
 
Windows 8 Platform NFC Development
Windows 8 Platform NFC DevelopmentWindows 8 Platform NFC Development
Windows 8 Platform NFC Development
 
NFC Development with Qt - v2.2.0 (5. November 2012)
NFC Development with Qt - v2.2.0 (5. November 2012)NFC Development with Qt - v2.2.0 (5. November 2012)
NFC Development with Qt - v2.2.0 (5. November 2012)
 
06 - Qt Communication
06 - Qt Communication06 - Qt Communication
06 - Qt Communication
 
05 - Qt External Interaction and Graphics
05 - Qt External Interaction and Graphics05 - Qt External Interaction and Graphics
05 - Qt External Interaction and Graphics
 
04 - Qt Data
04 - Qt Data04 - Qt Data
04 - Qt Data
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Java ME - 04 - Timer, Tasks and Threads

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