Threads: Three Loops Sequential Execution
Threads: Three Loops Sequential Execution
25-Oct-05 2
// second loop
for (int j=1; j<= 5; j++)
System.out.println(“second ” + j);
// third loop
for (int k=1; k<= 5; k++)
System.out.println(“third ” + k);
}
}
25-Oct-05 4
5 6
1
Java Threads Creating Threads in Java
Java includes built-in support for threading! Two approaches
Other languages have threads bolted-on to an existing structure Using Interface
Implement the runnable interface in a class
VM transparently maps threads in Java to OS threads Provide an implementation for the run() method
Allows threads in Java to take advantage of hardware and operating system Instantiate Thread object by passing runnable object in constructor
level advancements Start thread
Keeps track of threads and schedules them to get CPU time
Scheduling may be pre-emptive or cooperative
Using Inheritance
Subclass java.lang.Thread
Override the run() method
Instantiate Subclass Thread Object
Start thread
7 8
9 25-Oct-05
2
Thread Priorities Thread Priorities
Every Thread has a priority You can change thread priority by using any of the 3
predefined constants
Threads with higher priority are executed in preference
to threads with lower priority Thread.MAX_PRIORITY (typically 10)
Thread.NORM_PRIORITY (typically 5)
A thread’s default priority is same as of the creating Thread.MIN_PRIORITY (typically 1)
thread
13 14
Priority 9 C
Priority 7 D E F
Throws IllegalArgumentException if the priority is not in the range
MIN_PRIORITY to MAX_PRIORITY Priority 6 G
Thread.NORM_PRIORITY Priority 5 H I
For Example,
Priority 4
t.SetPriority(Thread.MAX_PRIORITY);
Priority 2 J K
t.setPriority(7);
Thread.MIN_PRIORITY Priority 1
15 16
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread. MAX_PRIORITY);
t1.start();
t2.start();
}
}
17 18
3
Thread Priorities
Problems
19 25-Oct-05
Causes the currently executing thread to wait for the High priority threads should execute sleep method after
time (milliseconds) specified some time to give low priority threads a chance to run
otherwise starvation may occur
Waiting is efficient (non-busy)
Sleep can be used for delay purpose
Threads come out of the sleep when the specified time
interval expires or when interrupted by some other i.e., anyone can call Thread.sleep
thread
Note that sleep throws InterruptedException. Need try/catch
Thread coming out of sleep may go to the running or
ready state depending upon the availability of the
processor.
21 22
23 24
Output: SleepEx.java Useful Thread Methods (cont.)
yield ( )
25 26
29 30
5
Thread life-cycle statechart diagram Thread Lifecycle
start()
Born
start new
Ready
I/O completed
ready
thread dispatch notify()
quantum expiration (assign a
yield processor) times expires
timeout expires
I/O completes
blocked
interrupt
notifyAll
interrupt
acquire lock
or interrupted
notify
en dispatch
Running te
r
stasyn
is
re sue te chr
m on waiting yield()
sleeping
qu I
com
es /O en iz
it
p
t t ed
ee
wa sleep()
ple
sl
te
wait() running
sleep interval When a thread completes
expires (returns from its run method),
interrupt it reaches the Dead state
(shown here as the final state)
run completes
dead
31 32
6
Output: JoinEx.java
Synchronization
37 25-Oct-05
other, or signaling one thread that the other thread has finished
The area where shared memory locations are modified doing something
are know as a critical section and only one thread should Done using join/wait/notify
able to enter the critical section at any given point in
time.
39 40
41 42
7
Reader/Writer Conflict Reader/Writer Conflict
Case Case
thread1 runs inc(), while thread2 runs sum()
thread2 could get an incorrect value if inc() is half way done thread1 runs inc() while thread2 runs inc() on the same object
This happens because the lines of sum() and inc() interleave The two inc()’s can interleave in order to leave the object in an
Note inconsistent state
Even a++ and b++ are not atomic statements
Therefore, interleaving can happen at a scale finer than a single statement! Again
a++ is really three steps: read a, increment a, write a a++ is not atomic and can interleave with another a++ to
Java guarantees 4-byte reads and writes will be atomic
This is only a problem if the two threads are touching the same object and
produce the wrong result
therefore the same piece of memory! This is true in most languages
43 44
45 46
47 48
8
Sychronized Method Picture Synchronized Method Example
synchronized method -- /*
acquire object lock A simple class that demonstrates using the 'synchronized'
keyword so that multiple threads may send it messages.
thread run { The class stores two ints, a and b; sum() returns
thread run { -- their sum, and inc() increments both numbers.
-- --
-- } <p>
} ivar The sum() and incr() methods are "critical sections" --
they compute the wrong thing if run by multiple threads
ivar at the same time. The sum() and inc() methods are declared
"synchronized" -- they respect the lock in the receiver object.
*/
synch a() { class Pair {
-- private int a, b;
--
} public Pair() {
a = 0;
object lock b = 0;
}
49 50
51 52
53 54
9
Producer/Consumer Relationship
Consider a Producer/Consumer relationship in which a producer
thread deposits a sequence of numbers into a slot of shared
memory
Producer/Consumer Relationship The consumer thread reads this data from the shared memory and
prints that data.
Problems
If the threads are not synchronized, data can be lost if the producer places
new data into the shared slot before the consumer consumes the previous
data
Data can be doubled if the consumer consumes the data again before the
producer produces the next item.
25-Oct-05 56
Example Code
notify( ) / notifyAll( )
One thread in the waiting state for a particular object becomes ready on a
Producer/Consumer Relationship call to notify( ) issued by another thread associated with that object.
If a thread calls notifyAll( ), then all threads waiting for the object are
placed in the ready state.
25-Oct-05 58
25-Oct-05 60
10