Multithreading I
Multithreading I
Multithreaded Programming
• Unlike many other computer languages, Java provides built-in
support for multithreaded programming.
2
Multithreaded Programming
• In a thread-based multitasking, a single program can perform 2
or more tasks simultaneously.
• For instance, a text editor can format text at the same time that it
is printing, as long as these two actions are being performed by
two separate threads.
Thread States
• Born State
Thread was just created
• Ready State
Thread’s start method invoked
Thread can now execute
• Running State
Thread is assigned a processor and running
• Dead State
Thread has completed or exited
Eventually disposed of by system
Thread States: Life Cycle of a Thread
start
read y
q uantum
exp iratio n d isp atch
I/ O
yield (a ssig n a
Al l
co
inte rrup t p roce ssor)
ot i y
mp
t if
fy
running
let
no
ion
issu
eI
n
/O
or
co
it re q
wa ue
m
p
st
ee
ple
sl
te
wa iting slee ping de ad blocked
7
Synchronization
8
The Thread Class and the Runnable
Interface
• Java’s multithreading system is built upon the Thread class, its
methods, and its companion interface, Runnable.
11
Creating a Thread
12
Implementing Runnable
• The easiest way to create a thread is to create a class that implements
the Runnable interface. Runnable abstracts a unit of executable
code. You can construct a thread on any object that implements
Runnable. To implement Runnable, a class need only implement a
single method called run(), which is declared like this:
• Inside run(), you will define the code that constitutes the new
thread. It is important to understand that run() can call other
methods, use other classes, and declare variables, just like the main
thread can. The only difference is that run() establishes the entry
point for another, concurrent thread of execution within your
program. This thread will end when run() returns.
13
Choosing an Approach
At this point, you might be wondering why Java has 2 ways to create
child threads, and which approach is better. The answers to these
questions turn on the same point. The Thread class defines several
methods that can be overridden by a derived class. Of these methods,
the only one that must be overridden is run(). This is of course, the
same method required when you implement Runnable. Many Java
programmers feel that classes should be extended only when they are
being enhanced or modified in some way. So, if you will not be
overriding any of Thread’s other methods, it is probably best simply to
implement Runnable. This is up to you, of course. However,
throughout the rest of the programs, we will create threads by using
classes that implement Runnable.
14