MobAppDev (Fall 2014): Shared Agendas, Loopers, Handlers, & Threads
MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads
-
Upload
vladimir-kulyukin -
Category
Technology
-
view
119 -
download
0
description
Transcript of MobAppDev (Fall 2014): Threads, Static & Non-Static Synchronization, Concurrency & Threads
MobAppDev
Threads, Static & Non-Stastic Synchronization, Concurrency &
Threads
Vladimir Kulyukin
www.vkedco.blogspot.com
Outline● Threads● Static & Non-Static Synchronization● Concurrency & Threads
Threads
Thread Behavior● Each thread starts and runs to completion● A thread finishes when its run() method finishes● A thread can never be re-started (calling start() more than once on
the same Thread object throws IllegalThreadStateException)● The order in which the Runnable threads get to run is JVM-specific
Thread Behavior● When a Thread goes to sleep (Thread.sleep() is executed) and
wakes up, it does not start running – it becomes Runnable and may be selected to run by the JVM scheduler
● A yielding Thread (Thread.yield() is executed) yields to the Threads with the same priorities but there is no guarantee that another Thread will be chosen by the JVM scheduler – the same Thread (the one that just yielded) may be chosen to run again and again
Static & Non-Static Syncrhonization
When Should I Synchronize?● Any time when multiple threads are accessing and modifying the
same data● Any time when there is a race condition: multiple threads render the
data inconsistent● Race condition example: Two threads A and B manipulate the
same book database. A reads a book's price and goes to sleep. B modifies the book's price. A wakes up and orders the book on the basis of the old price.
How to Synchronize in Java● Every Java Instance Object and Java Class Object has a
built-in lock● Non-static methods should synchronize on Instance Objects
(this Object)● Static methods should synchronize on Class Objects● Since there is only one lock per Object, once a Thread picks
up the lock, no other thread can enter until the first Thread finishes
How to Synchronize: Blocks & Methods
// Here is an example of a synchronized block
class MySync {
public void myMethod() {
synchronized(this) {
// do some stuff here
}
}
}
// Here is an example of a synchronized method
class MySync {
public void synchronized myMethod() {
// do some stuff here
}
}
How to Synchronize: Static Blocks & Methods
// example of a synchronized static block
class MyStaticSync {
static int mInt = 0;
public static int getInt() {
synchronized(MyStaticSync.class) {
return mInt;
}
}
}
// Example of a synchronized static method
class MyStaticSync {
static int mInt = 0;
public static synchronized int getInt() {return mInt;
}
}
How Threads Sync● Threads calling non-static synchronized methods/blocks block each
other if they synchronize on the same Instance Objects● Threads calling static synchronized methods/blocks block each other
if they synchronize on the same Class Objects● Threads executing static and non-static methods/blocks NEVER
block each other● Rule of Thumb: Be careful when mixing static and non-static
synchronization and check which Thread synchronizes on which object
Concurrency & Threads
Concurrent vs. Parallel
● The term concurrent typically means that processes and threads share the same CPU (or a limited number of CPUs)
● The term parallel typically means that processes and threads run on different CPUs
● Concurrent processes and threads simulate parallelism
Concurrency in Java
● Concurrency in Java is realized via Threads● When it comes to concurrency in Java , the basic rule to
remember is that the order in which threads execute is never guaranteed
● The actual order of thread execution depends on the specific JVM scheduler and on the priorities of other concurrent threads
Joining Threads
● Thread.join() is the method that allows one thread to wait until another thread completes
● th.join(): the current thread waits until thread th completes
● th.join(int wait_time): wait_time specifies the waiting period (in milliseconds) for the current thread
Exampleclass MyJob implements Runnable {
int mUpperBound = 0; long mSum = 0;
public MyJob(int upper) { mUpperBound = upper; }
@Override
public void run() {
Log.d(ThreadTesterActivity.LOGTAG, Thread.currentThread().getName() + " running");
for(int i = 1; i < mUpperBound; i++) { mSum += i; }
Log.d(ThreadTesterActivity.LOGTAG, Thread.currentThread().getName() + " done");
}
}
long getSum() { return mSum; }
}
Example
source code is in ThreadTester.java
Example: Non-guaranteed Execution// Thread execution order is not guaranteed
Log.d(ThreadTesterActivity.LOGTAG, Thread.currentThread().getName() + " running");
MyJob job01 = new MyJob(100); // First Job
MyJob job02 = new MyJob(200); // Second Job
new Thread(job01, "Thread01").start(); // First Job Mounted on a Thread
new Thread(job02, "Thread02").start(); // Second Job Mounted on a Thread
Log.d(ThreadTesterActivity.LOGTAG, "job01's sum = " + job01.getSum());
Log.d(ThreadTesterActivity.LOGTAG, "job02's sum = " + job02.getSum());
source code is in ThreadTester.java
Example: Ordered Execution// Thread execution order is explicitly guaranteed with joins
MyJob job01 = new MyJob(100); MyJob job02 = new MyJob(200);
Thread thread01 = new Thread(job01, "Thread01");
Thread thread02 = new Thread(job02, "Thread02");
thread01.start(); thread02.start();
try {
thread01.join(); // main thread waits until thread01 completes
thread02.join(); // main thread waits until thread02 completes
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(ThreadTesterActivity.LOGTAG, "job01's sum = " + job01.getSum());
Log.d(ThreadTesterActivity.LOGTAG, "job02's sum = " + job02.getSum());
source code is in ThreadTester.java