SlideShare a Scribd company logo
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

More Related Content

Viewers also liked

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
Andreas Jakl
 
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
Andreas Jakl
 
Java ME - 08 - Mobile 3D Graphics
Java ME - 08 - Mobile 3D GraphicsJava ME - 08 - Mobile 3D Graphics
Java ME - 08 - Mobile 3D Graphics
Andreas Jakl
 
Java ME - 05 - Game API
Java ME - 05 - Game APIJava ME - 05 - Game API
Java ME - 05 - Game API
Andreas Jakl
 
Java ME - 01 - Overview
Java ME - 01 - OverviewJava ME - 01 - Overview
Java ME - 01 - Overview
Andreas Jakl
 
Java ME - 02 - High Level UI
Java ME - 02 - High Level UIJava ME - 02 - High Level UI
Java ME - 02 - High Level UI
Andreas Jakl
 
Paradise Lost
Paradise LostParadise Lost
Paradise Lostjanewoo
 

Viewers also liked (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
 

Similar to Java ME - 04 - Timer, Tasks and Threads

Symbian OS - Active Objects
Symbian OS - Active ObjectsSymbian OS - Active Objects
Symbian OS - Active Objects
Andreas Jakl
 
Symbian OS - Memory Management
Symbian OS - Memory ManagementSymbian OS - Memory Management
Symbian OS - Memory Management
Andreas Jakl
 
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
Simon Maple
 
Microservices with Micronaut
Microservices with MicronautMicroservices with Micronaut
Microservices with Micronaut
QAware GmbH
 
REAL TIME OPERATING SYSTEM
REAL TIME OPERATING SYSTEMREAL TIME OPERATING SYSTEM
REAL TIME OPERATING SYSTEMprakrutijsh
 
Microservices with Micronaut
Microservices with MicronautMicroservices with Micronaut
Microservices with Micronaut
QAware GmbH
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
Neeraj Kaushik
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS MultithreadingRicha Jain
 
Developing Async Sense
Developing Async SenseDeveloping Async Sense
Developing Async Sense
Nemanja Stojanovic
 
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
WebStackAcademy
 
Object - Based Programming
Object - Based ProgrammingObject - Based Programming
Object - Based Programming
Andy Juan Sarango Veliz
 
JavaFX Pitfalls
JavaFX PitfallsJavaFX Pitfalls
JavaFX Pitfalls
Alexander Casall
 
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
Ben Hall
 
The Pillars Of Concurrency
The Pillars Of ConcurrencyThe Pillars Of Concurrency
The Pillars Of Concurrencyaviade
 
Tech talk
Tech talkTech talk
Tech talk
Preeti Patwa
 
Computer Networks Omnet
Computer Networks OmnetComputer Networks Omnet
Computer Networks Omnet
Shivam Maheshwari
 
Javascript Stacktrace Ignite
Javascript Stacktrace IgniteJavascript Stacktrace Ignite
Javascript Stacktrace Ignite
Eric Wendelin
 
Threaded Programming
Threaded ProgrammingThreaded Programming
Threaded ProgrammingSri Prasanna
 
03 objective-c session 3
03  objective-c session 303  objective-c session 3
03 objective-c session 3
Amr Elghadban (AmrAngry)
 

Similar to 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
 

More from Andreas Jakl

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
Andreas Jakl
 
AR / VR Interaction Development with Unity
AR / VR Interaction Development with UnityAR / VR Interaction Development with Unity
AR / VR Interaction Development with Unity
Andreas Jakl
 
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
Andreas Jakl
 
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
Andreas Jakl
 
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
Andreas Jakl
 
Android and NFC / NDEF (with Kotlin)
Android and NFC / NDEF (with Kotlin)Android and NFC / NDEF (with Kotlin)
Android and NFC / NDEF (with Kotlin)
Andreas Jakl
 
Basics of Web Technologies
Basics of Web TechnologiesBasics of Web Technologies
Basics of Web Technologies
Andreas Jakl
 
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
Andreas Jakl
 
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?
Andreas Jakl
 
Mobile Test Automation
Mobile Test AutomationMobile Test Automation
Mobile Test Automation
Andreas Jakl
 
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...
Andreas Jakl
 
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
Andreas Jakl
 
Nokia New Asha Platform Developer Training
Nokia New Asha Platform Developer TrainingNokia New Asha Platform Developer Training
Nokia New Asha Platform Developer Training
Andreas Jakl
 
Windows Phone 8 NFC Quickstart
Windows Phone 8 NFC QuickstartWindows Phone 8 NFC Quickstart
Windows Phone 8 NFC Quickstart
Andreas Jakl
 
Windows (Phone) 8 NFC App Scenarios
Windows (Phone) 8 NFC App ScenariosWindows (Phone) 8 NFC App Scenarios
Windows (Phone) 8 NFC App Scenarios
Andreas Jakl
 
Windows 8 Platform NFC Development
Windows 8 Platform NFC DevelopmentWindows 8 Platform NFC Development
Windows 8 Platform NFC Development
Andreas Jakl
 
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)
Andreas Jakl
 
06 - Qt Communication
06 - Qt Communication06 - Qt Communication
06 - Qt Communication
Andreas Jakl
 
05 - Qt External Interaction and Graphics
05 - Qt External Interaction and Graphics05 - Qt External Interaction and Graphics
05 - Qt External Interaction and Graphics
Andreas Jakl
 
04 - Qt Data
04 - Qt Data04 - Qt Data
04 - Qt Data
Andreas Jakl
 

More from 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
 

Recently uploaded

Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
ViralQR
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 

Recently uploaded (20)

Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 

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