Mobile Computing Dr. Mohsin Ali Memon
Threads • Basic approach - Make a task list with Executors.newFixedThreadPool - Add tasks to list with taskList.execute(someRunnable) • Three variations on the theme - Separate classes that implement Runnable - Main Activity implements Runnable - Inner classes that implement Runnable - Race conditions and synchronization • Related topics - Helpful Thread-related methods
Motivation for Concurrent Programming • Pros - Advantages even on single-processor systems • Efficiency - Downloading image files • Convenience - A clock icon • Responsiveness - If you block the main thread, event handlers will not respond - Some devices have multiple cpus or cores • Find out via Runtime.getRuntime().availableProcessors() • Cons - Significantly harder to debug and maintain than single- threaded apps
Steps for Concurrent Programming
Steps for Concurrent Programming cont’d
Approach One: Separate Classes that Implement Runnable
Separate Runnable Class: Template Code This code should not update the UI. If you need to update UI, use AsyncTask class.
Thread Mechanism One: Example
Thread Mechanism One: Example con’d
Helper Class
Thread Mechanism One: Example Result
Pros and Cons of Approach
Approach Two: Main App Implements Runnable
Main App Implements Runnable: Template Code
Thread Mechanism Two: Example
Thread Mechanism Two: Results
Pros and Cons of Approach
Approach Three: Inner Class that Implements Runnable
Inner Class implements Runnable: Template code
Thread Mechanism Three: Example
Thread Mechanism Three: Example cont’d
Thread Mechanism Three: Example Result
Pros and cons of approach
Summary
Race Condition
Race Conditions: Example
Race Conditions: Example cont’d
Race Conditions: Result
Race Conditions: Solution
Race Conditions: Solution
Helpful –Thread related Methods
Methods in ExecutorService Class
Threads Cannot Update UI
Updating UI All at Once
Displaying a network image
BitmapUtils: Getting a Bitmap
Making a View for an Image
BitmapUtils:Getting a view for image
Example: Unthreaded Image Viewer
Activity
Results
Updating UI with View.post
Example: Multithreaded Image Viewer
Main Activity
Main Activity Button Handler
Main Activity: Runnable Inner Class (For Background)
Main Activity: Runnable Inner Class (For UI Thread)
Results
Downloading Images via AsyncTask