Multi Threading
Multi Threading
Class Thread
Interface Runnable
OOP: Multithreading
Thread
Definition: A thread is a single sequential flow of
control within a program (also called lightweight
process).
OOP: Multithreading
Responsiveness
Resource sharing
Economy
Utilization of multiprocessor architectures
Disadvantages
n
n
OOP: Multithreading
code
data
files
code
data
files
thread
single-threaded
OOP: Multithreading
multi-threaded
Examples
u
u
u
Examples
u
u
u
OOP: Multithreading
Windows 95/98/NT/2000
Solaris
TRU64 (Compaq UNIX)
Solaris 2 Threads
light weight
process
user threads
task 1
task 3
task 2
kernel threads
kernel
cpu
OOP: Multithreading
cpu
cpu
cpu
Java Threads
Java threads may be created by
n
n
OOP: Multithreading
Class Thread
The simplest way to make a thread
Treats a thread as an object
Override the run( ) method, i.e., the threads main
n
n
Typically a loop
Continues for the life of the thread
OOP: Multithreading
10
Sharing Resources
Single threaded programming: you own everything, no
First thread that acquires the lock gains control of the object,
and the other threads cannot call synchronized methods for
that object.
OOP: Multithreading
11
Locks
One lock pr. object for the objects methods.
One lock pr. class for the classs static methods.
Typically data is private, only accessed through
methods.
If a method is synchronized, entering that method
acquires the lock.
n
OOP: Multithreading
12
Efficiency
n
OOP: Multithreading
Older standard Java libraries used synchronized a lot, did not provide
any alternatives.
13
14
OOP: Multithreading
15
16
OOP: Multithreading
17
OOP: Multithreading
18
19
20
running thread.
sleep() puts the currently running thread to sleep for a
specified amount of time.
resume() resumes execution of a suspended thread.
stop() stops execution of a thread.
start()
new
new
runnable
sleep()
suspend()
wait()
return/stop()
resume()
notify()
dead
blocked
OOP: Multithreading
21
Summary
Single-threaded programming: live by all by your self,
own everything, no contention for resources.
language.
Multithreading makes Java programs complicated
n
OOP: Multithreading
22