You are on page 1of 22

Multithreading

By
A. Ngorora

ITDS301 1
Agenda
O Introduction
O Thread concepts
O Creating Tasks and Threads
O The Thread class
O Thread class methods
O Thread states
O Life cycle of threads

ITDS301 2
Introduction
O Multithreading is the concurrent running
of multiple tasks within a program

O Performing operations concurrently (in


parallel)
O We can walk, talk, breathe, see, hear,
smell... all at the same time
O Computers can do this as well - download
a file, print a file, receive email, run the
clock, more or less in parallel….

ITDS301 3
Processes vs tasks

O Processes
O Operating systems support processes
O Processes have their own memory space
O Heavy-weight

O Tasks
O Tasks share memory space
O Light-weight

ITDS301 4
Thread concepts
O A Thread is the flow of execution,
from beginning to end, of a task.

O A thread provides the mechanism for


running a task

O Java exceptionally good at creating


and running threads and for locking
resources to prevent conflicts
ITDS301 5
Single vs multiprocessors
O Multiprocessor (CPU)

Thread 1
Thread 2
Thread 3

O Single processor (CPU) – time


sharing
Thread 1
Thread 2
Thread 3
ITDS301 6
Advantages of Multithreading
O More responsive to user input – GUI
application can interrupt a time-
consuming task
O More interactive
O Better performance
O Reactive systems – constantly monitoring
O Server can handle multiple clients
simultaneously
O Can take advantage of parallel processing

ITDS301 7
Creating tasks and threads
O Tasks are objects

O To create tasks:
O Define a class for tasks
O Which implements the Runnable interface

O Runnable interface is simple. Contains a run


method
O Implement this method…. run().. Tell how
thread is going to run
ITDS301 8
Template for task class
java.lang.Runnable TaskClass // Client class
public class Client {
...
// Custom task class public void someMethod() {
public class TaskClass implements Runnable { ...
... // Create an instance of TaskClass
public TaskClass(...) { TaskClass task = new TaskClass(...);
...
} // Create a thread
Thread thread = new Thread(task);
// Implement the run method in Runnable
public void run() { // Start a thread
// Tell system how to run custom thread thread.start();
... ...
} }
... ...
} }

ITDS301 9
Defining a task & thread
O Define Task class
O Then create task by calling constructor
O TaskClass task = new TaskClass(…);
O Task must be executed in thread

O Thread class contains constructors for


creating threads and many useful methods
for controlling them
O Create thread:
O Thread thread = new Thread(task);

ITDS301 10
Starting the thread
O Invoke start method to tell JVM that
thread is ready to run
O thread.run();

O The JVM will execute the task by


invoking the task’s run method

ITDS301 11
States of thread
O New
O Ready
O Running
O Blocked (sleep, wait)
O Dead / finished

ITDS301 12
Thread States

yield(), or Running
time out run() returns
Thread created start()
New Ready run() join() Finished

interrupt() sleep()
Target wait()
finished

Wait for target Wait for time Wait to be


to finish out notified
Time out notify() or
notifyAll()
Blocked
Interrupted()

ITDS301 13
Thread Class
«interface»
java.lang.Runnable

java.lang.Thread
+Thread() Creates a default thread.
+Thread(task: Runnable) Creates a thread for a specified task.
+start(): void Starts the thread that causes the run() method to be invoked by the JVM.
+isAlive(): boolean Tests whether the thread is currently running.
+setPriority(p: int): void Sets priority p (ranging from 1 to 10) for this thread.
+join(): void Waits for this thread to finish.
+sleep(millis: long): void Puts the runnable object to sleep for a specified time in milliseconds.
+yield(): void Causes this thread to temporarily pause and allow other threads to execute.
+interrupt(): void Interrupts this thread.
ITDS301 14
Thread methods (I)
O isAlive() - method used to find out
the state of a thread

O returns true:
O thread is in the Ready, Blocked, or
Running state

O returns false:
O thread is new and has not started or if it is
ITDS301 finished 15
Thread methods (II)
O The sleep(long millisec) method
puts the thread to sleep for the
specified time to allow other threads
to execute
O InterruptedException
O When sleeping thread’s interrupt()
method is called
O Rarely happens
O But must put this checked exception
in try catch
ITDS301 16
Thread methods (III)
O yield() method temporarily releases
time for other methods

O join() method – forces one thread to


wait for another thread to finish

ITDS301 17
Thread methods (IV)
O interrupt()
O If a thread is currently in the Ready
or Running state, its interrupted flag
is set
O If a thread is currently blocked, it is
awakened and enters the Ready
state
O and an java.io.InterruptedException
is thrown
ITDS301 18
Thread priorities
O Java assigns every thread a priority
O By default, inherits the priority of the thread that
spawned it
O You can change priority
O setPriority()
O You can read the priority
O getPriority()
O Priorities are numbers from 1 – 10
O Constants:
O MIN_PRIORITY - 1
O MAX_PRIORITY - 10
O NORM_PRIORITY – 5 (default)

ITDS301 19
Scheduling
O JVM picks the currently runnable thread
with the highest priority
O Lower-priority thread can only run when
no higher-priority threads are running
O Equal: round-robin scheduling
O Equal portions of CPU
O Circular queue
O Contention/starvation:
O A thread may never get a chance to run

ITDS301 20
Summary
O CREATE A TASK CLASS
O 1. Create a task class and implements the
Runnable interface
O 2. override the run() method to include the
tasks associated with the thread
APPLICATION/APPLET.
O create a thread for the task by creating an
object of the Thread class
O Wrap the task in this object
O start the thread
O manage the scheduling

ITDS301 21
Practical
O Complete programming exercise
32.7 p. 1197
O Extension of Applet program in
chapter 18, 18.14 p. 727

ITDS301 22

You might also like