Download as pdf or txt
Download as pdf or txt
You are on page 1of 46

Course Title: Java Programming.

Credit Hour: 3 hrs.


ECTS: 5 [2 Lecture , 3 Lab and 2 Tutorial Hours]
Lecture Schedule: Every _____________

Bedasa Wayessa

Java Programming CoSc3053 1


Chapter 5
Multithreading
Concepts

Java Programming CoSc3053 2


Objectives
 Thread vs process
 Overview of multithreading
 Thread Life Cycle
 Thread priorities
 Thread synchronization

Java Programming CoSc3053 3


Overviews
 There are 3 levels of executions of computer instructions on a computer
system:
 CPU Level: There is only one flow of execution on the central processing unit
(CPU), that is the operating system (OS).
 OS Level: For a multi-tasking OS, multiple application programs can be managed to
be executed simultaneously.
 Here, a flow of execution is called a process.
 Application Level: For a well written application program, multiple sections of codes
can be managed to be executed simultaneously.
 Here, a flow of execution is called a thread.
 A program that can manage multiple threads is called a multi-threading
program.
 A good example of multi-threading programs are computer games that simulate real
time activities of multiple human characters and/or moving objects.

Java Programming CoSc3053 4


Thread vs process
 Process:
– A process is an active program
• i.e. a program that is under execution.
– It is more than the program code as it includes the program counter, process
stack, registers, program code etc.
– Compared to this, the program code is only the text section.
– Processes require more time for context switching as they are more heavy.
– Processes are totally independent and don’t share memory.
– Communication between processes requires more time than between
threads.
– Processes require more resources than threads.
– Processes require more time for creation and termination

Java Programming CoSc3053 5


Thread vs process
 Thread:
– A thread is a single flow of control like simple program.
– A thread is a lightweight process that can be managed independently by a
scheduler.
– A thread may share some memory with its peer threads.
– Communication between threads requires less time than between
processes .
– Threads generally need less resources than processes.
– Threads require less time for creation and termination.

Java Programming CoSc3053 6


Thread vs process
 Thread: What are Threads Good For?
– To maintain responsiveness of an application during a long running task
– To enable cancellation of separable tasks
– Some problems are naturally parallel
– To monitor status of some resource (e.g., DB)
– Some APIs and systems demand
– Single-user programs/clients
• continuously responsive user interfaces
– e.g., make help menu accessible during time-consuming
database operation, etc.
– Speed up tasks when multiple processors available
– Servers
• Allows multiple client connections simultaneously

Java Programming CoSc3053 7


Multithreading
 Multithreading enables multiple tasks in a program to be executed
concurrently.
 Powerful features of Java is its built-in support for multithreading
 The concurrent running of multiple tasks within a program.
 A program may consist of many tasks that can run concurrently.
 A thread is the flow of execution, from beginning to end, of a task.

(a) Here multiple threads are running on multiple CPUs. (b) Here multiple
threads share a single CPU.
Java Programming CoSc3053 8
Multithreading
 More than one thread (program) run simultaneously is known as
multithreading (multiprogramming).
 In multithreading java interpreter handles the switching of control
between the threads in such a way that it looks like they are running
concurrently.
 Multithreading is useful in a number of ways. We can divide a long
program into number of threads and executes them in parallel.
 We are going to learn so many useful things in thread lets start with
single main thread.

Java Programming CoSc3053 9


Multithreading
 When we execute an application:
1. The JVM creates a Thread object whose task is defined by the main()
method
2. The JVM starts the thread
3. The thread executes the statements of the program one by one
4. After executing all the statements, the method returns and the thread dies
 Multiple Threads in an Application
 Each thread has its private run-time stack
 If two threads execute the same method, each will have its own copy of
the local variables and the methods
 However, all threads see the same dynamic memory, i.e., heap
 Two different threads can act on the same object and same static fields
concurrently

Java Programming CoSc3053 10


The Main Thread
 When our simple program starts, one single thread begins running
immediately.
 This is called our single main thread.
 The main thread is created automatically when program is started.
 It is very important thread because of two reason.
1. From the main thread other child thread will be created.
2. Main thread is all most every time stop running lastly because it
has to remove or shutdown few resources as well as few action.
 Now the question is how can we control our main thread?
 Actually by calling the method currentThread() of Thread class we
can control our main thread.
Java Programming CoSc3053 11
Thread Life Cycle
 A thread goes through various stages in its life cycle.
 For example, a thread is born, started, runs, and then dies.
 The following diagram shows the complete life cycle of a thread.

 A thread can be in one of five states:


 New, Ready, Running, Blocked, or Finished.
Java Programming CoSc3053 12
Thread Life Cycle
 New
 A new thread begins its life cycle in the new state.
 It remains in this state until the program starts the thread.
 It is also referred to as a born thread.
 Runnable
 After a newly born thread is started, the thread becomes runnable.
 A thread in this state is considered to be executing its task.
 Waiting
 Sometimes, a thread transitions to the waiting state while the thread
waits for another thread to perform a task.
 A thread transitions back to the runnable state only when another
thread signals the waiting thread to continue executing.
Java Programming CoSc3053 13
Thread Life Cycle
 Timed Waiting
 A runnable thread can enter the timed waiting state for a specified
interval of time.
 A thread in this state transitions back to the runnable state when
that time interval expires or when the event it is waiting for occurs.
 Terminated (Dead)
 A runnable thread enters the terminated state when it completes its
task or otherwise terminates.

Java Programming CoSc3053 14


Creating Thread
 We can create thread in java with two different ways.
1. Extending the Thread Class.
2. Implements runnable interface.
1. Extending the Thread Class.
 This approach provides more flexibility in handling multiple
threads created using available methods in Thread class.
 This approach allows you to override the methods in the Thread
class to perform the functions you define for your program.

Java Programming CoSc3053 15


Creating Thread by Extending the Thread
 The Thread class contains the constructors for creating threads for
tasks and the methods for controlling threads.

Define a thread class by extending the Thread class.


Java Programming CoSc3053 16
Creating Thread by Extending the Thread
package MultiThreading;

public class ThreadDemo extends Thread {

public void run(){


System.out.println("This is from secondary Thread :
"+Thread.currentThread().getName());
}
public static void main(String[] args) {

ThreadDemo thread = new ThreadDemo();

thread.start();

System.out.println("This is from Main Thread :


"+Thread.currentThread().getName());
}
}

run:
This is from Main Thread : main
Output This is from secondary Thread : Thread-0
Java Programming CoSc3053 17
Creating Thread by Extending the Thread
package MultiThreading;

public class NamesThread extends Thread {

public void run() {


System.out.println("Hello " + Thread.currentThread().getName());
}

public static void main(String args[]) {


NamesThread names = new NamesThread();

Thread firstThread = new Thread(names, "Duressa");


Thread secondThread = new Thread(names, "Tesfanesh");

firstThread.start();
secondThread.start();
while (secondThread.isAlive() && firstThread.isAlive()) {
System.out.println("First Thread is " + firstThread.getState());
System.out.println("second Thread is " + secondThread.getState());
}
firstThread.stop(); First Thread is RUNNABLE
secondThread.stop(); Hello Tesfanesh
}
Hello Duressa
} second Thread is RUNNABLE

Java Programming CoSc3053 18


Creating Thread by Extending the Thread
 The class ThreadDemo subclasses the Thread class and overrides
the run() method defined by the Thread class.
 Because ThreadDemo is derived from Thread, it inherits all of the
methods defined in Thread including start(), run(), and stop().
 The original versions of these methods defined in Thread are used
except in the case of the run() method, which has been overridden.
 Because this method tells the thread which operations to perform
after the thread has been started, it typically needs to be overridden.

This approach is, however, not recommended because it mixes the task and the mechanism
of running the task. Separating the task from the thread is a preferred design.

Java Programming CoSc3053 19


Creating Thread by Implementing Runnable
 In this method we have one interface named runnable and we implements
this interface for implementing a thread.
 Create one class which implements runnable interface.
 Override the run() method and put some line of code for that particular
thread.
 Now create an object of inbuilt thread class and create an object of class
that implements runnable interface.
 Give the reference of object to thread object by passing an argument
(argument must be the object of class which implements the runnable
interface) while creating a thread object.
 Call the start() method to run the thread.

Java Programming CoSc3053 20


Creating Thread by Implementing Runnable
 A task class must implement the Runnable interface.
 A task must be run from a thread.
 Tasks are objects.
 To create tasks, you have to first define a class for tasks, which implements
the Runnable interface.
 The Runnable interface is rather simple.
 All it contains is the run method.
 You need to implement this method to tell the system how your thread is
going to run.

Define a task class by implementing the Runnable interface.

Java Programming CoSc3053 21


Creating Thread by Implementing Runnable
package MultiThreading;

public class ThreadRunnable implements Runnable {

public void run() {


System.out.println("This is from scondary Thread : " +
Thread.currentThread().getName());
}

public static void main(String[] args) {


ThreadDemo thread = new ThreadDemo();

thread.start();
System.out.println("This is from Main Thread : " +
Thread.currentThread().getName());
}

run:
This is from Main Thread : main
Output This is from secondary Thread : Thread-0
Java Programming CoSc3053 22
Creating Thread by Implementing Runnable
package MultiThreading; run:
public class NamesRunnable implements Runnable {
Hello Duressa
First Thread is RUNNABLE
public static void main(String args[]) { Hello Tesfanesh
NamesThread names = new NamesThread(); second Thread is RUNNABLE
Thread firstThread = new Thread(names, "Duressa");
Thread secondThread = new Thread(names, "Tesfanesh");

firstThread.start();
secondThread.start();
while (secondThread.isAlive() && firstThread.isAlive()) {
System.out.println("First Thread is " + firstThread.getState());
System.out.println("second Thread is " + secondThread.getState());
}
firstThread.stop();
secondThread.stop();
}

public void run() {


System.out.println("Hello " + Thread.currentThread().getName());
}
}

Java Programming CoSc3053 23


Creating Thread by Implementing Runnable
 The advantage of this approach is that you can create a new class that
is both derived from another class and uses the methods defined by
the Runnable interface.
 That class then implements the run method.
 An instance of the class can then be allocated, passed as an argument
when creating Thread, and started.
 It has only abstract method run().
 Multiple threads share the same objects.
 If a class is implementing the runnable interface then your class can
extend another class.

Java Programming CoSc3053 24


Extending Thread vs Runnable Interface
 Choosing between these two is a matter of taste
 Implementing the Runnable interface
 May take more work since we still
 Declare a Thread object
 Call the Thread methods on this object
 Your class can still extend other class
 Extending the Thread class
 Thread is a class. It is used to create a thread.
 It has multiple methods including start() and run().
 Each thread creates a unique object and gets associated with it.
 Easier to implement
 Your class can no longer extend any other class

Java Programming CoSc3053 25


The Thread Class: Constructor and constants

 Choosing between these two is a matter of taste


 Implementing the Runnable interface
 May take more work since we still

 Declare a Thread object


 Call the Thread methods on this object
 Your class can still extend other class
 Extending the Thread class
 Thread is a class. It is used to create a thread.
 It has multiple methods including start() and run().
 Each thread creates a unique object and gets associated with it.
 Easier to implement
 Your class can no longer extend any other class

Java Programming CoSc3053 26


Thread Priority
 Each java thread has its own priority which decides the order of thread to be
schedule.
 The threads of equal priority will be given same treatment by java scheduler. And they
will follow the FCFS (First Come First Serve) algorithm.
 User can also set the priority of thread by using the setPriority() method as follow:
 ThreadName.setPriority(int Number);
 Here the number is integer value between 1 to 10, Here 1 is minimum priority 10 is
maximum priority.
 The Thread class defines few priority constants:
 MIN_PRIORITY = 1
 NORM_PRIORITY = 5
 MAX_PRIORITY = 10
 In any Thread the default priority is NORM_PRIORITY

Java Programming CoSc3053 27


Thread Priority
 In multithreading by assigning priority we can answer an input as
quickly as we want.
 Whenever more than one threads are ready to run java system select
the highest priority thread and execute it
 If another thread of higher priority comes ,the running thread will be
preempted(blocked) by the incoming thread and current thread will
move to runnable state.

Java Programming CoSc3053 28


Thread Priority
 In multithreading
package by
MultiThreading; assigning priority we can answer an input as quickly as
we class
public want. Thread_A extends Thread {
public void run() {
System.out.println("ThreadTA strated");
 Whenever more than one threads are ready to run java system select
for (int i = 1; i <= 5; i++) {
the
System.out.println("\t From ThreadTA i = " + i);
highest
}
priority thread and execute it
System.out.println("Exit from TA");
 If} another thread of higher priority comes ,the running thread will be
}
preempted(blocked) by the incoming thread and current thread will move to
runnable
package state.
MultiThreading;

public class Thread_B extends Thread {


public void run() {
System.out.println("ThreadTB strated");
for (int j = 1; j <= 5; j++) {
System.out.println("\t From ThreadTB j = " + j);
}
System.out.println("Exit from TB");
}

Java Programming CoSc3053 29


Thread Priority
package MultiThreading;
Start Thread TA
public
 In class ThreadPriorityof_A_and_B
multithreading {
by assigning priority we can answer anThread
Start inputTBas quickly as
End of main Thread
we want.
public static void main(String[] args) { ThreadTB strated
Thread_A threadTA = new Thread_A(); From ThreadTB j = 1
 Whenever more than one threads are
Thread_B threadTB = new Thread_B(); ready to run java system
ThreadTA strated
select the
From ThreadTB j = 2
highest priority thread and execute it
threadTA.setPriority(Thread.MIN_PRIORITY); From ThreadTA i = 1
threadTB.setPriority(threadTA.getPriority() From
 If another
+ 3); thread of higher priority comes ,the running thread willThreadTB
be j=3
From ThreadTB j = 4
preempted(blocked) by the incoming thread and current thread Fromwill
ThreadTA
movei =to
2
System.out.println("Start Thread TA"); From ThreadTB j = 5
threadTA.start();
runnable state. Exit from TB
From ThreadTA i = 3
System.out.println("Start Thread TB"); From ThreadTA i = 4
threadTB.start(); From ThreadTA i = 5
Exit from TA
System.out.println("End of main Thread");
}

Java Programming CoSc3053 30


Thread Class Methods
 In multithreading by assigning priority we can answer an input as quickly as
we want.  The resume() method is responsible for
reactivating a method that is asleep
 Whenever more than one threads are ready to run java system select the
 The destroy() Method: This method causes a thread
highest priority thread and execute it
to die without any cleanup operations being
performed
 If another thread of higher priority comes ,the running thread will be
preempted(blocked) by the incoming thread and current thread will move to
runnable state.

 The suspend() Method: This method suspends execution of a thread.


 The run() Method: This method defines the actions to take place during the life
of a thread.

Java Programming CoSc3053 31


Thread Synchronization
 Threads communicate primarily by sharing access to fields and the objects
reference fields refer to.
 This form of communication is extremely efficient, but makes two kinds of
errors possible:
– thread interference and memory consistency errors.
 The tool needed to prevent these errors is synchronization.
 A shared resource may be corrupted if it is accessed simultaneously by
multiple threads.
 Java uses monitors for thread synchronization.
 The sychronized keyword
– Every synchronized method of an object has a monitor
– One thread inside a synchronized method at a time
– All other threads block until method finishes
– Next highest priority thread runs when method finishes

Java Programming CoSc3053 32


Thread Synchronization
 Synchronizing Accesses to Shared Data.
– Consider an Account class which provides debit and credit
methods which change the balance
– If multiple Transaction threads want to access the same Account
object problems could arise
 "Atomic" Operations
– Operations that cannot be divided into "smaller" operations
– Example: for myBalance being accessed by either the debit()
or credit() methods at about the same time
• these methods are not atomic at the byte-code level
• each has about four separate steps
Java Programming CoSc3053 33
Thread Synchronization
 Non Atomic Operations in Separate Threads
– Assume credit() and debit() are in separate threads
– Both will
1. read the balance
2. create a temp value
3. add to (or subtract from) the temp value
4. replace the old balance with the temp value
– If each step is happening at about the same time
 each replaces the old balance with its own temp value without
knowing about the action of the other, giving an incorrect new
balance value !!!
Java Programming CoSc3053 34
Thread Synchronization
 Making Methods Atomic
 Use the keyword synchronized to declare each method that
accesses the critical information
class Account{
. . .
synchronized public void debit(double amount)
{ … }
synchronized public void credit(double amount)
{ … }
private myBalance;
}

Java Programming CoSc3053 35


Thread Synchronization
 Making Methods Atomic
 When a thread …
– sends a synchronized message to an object
– and … no other thread is executing a synchronized method on
that object
 Then …
– Java locks the object
– other synchronized methods cannot access the object until the
first terminates

Java Programming CoSc3053 36


Thread Synchronization Example
package MultiThreading;
public class Account {
public int balance;
public int accountNo;

void displayBalance() {
System.out.println("Account No: " + accountNo +
" Balance: " + balance);
}
//synchronized void deposit(int amount) {
void deposit(int amount) {
balance = balance + amount;
System.out.println(amount + " is deposited");
displayBalance();
}
void withdraw(int amount) {
balance = balance - amount;
System.out.println(amount + " is withdrawn");
displayBalance();
}
}
Java Programming CoSc3053 37
Thread Synchronization Example
package MultiThreading;

public class TDeposit extends Thread {


int amount;
Account account;

TDeposit(Account x, int amount) {


this.account = x;
this.amount = amount; //new Thread(this).start();
}
@Override
public void run() {
synchronized(account){
try {
sleep(2000);
} catch (InterruptedException e) {
System.out.println(e.getCause());
}
}
account.deposit(amount);
}
} Java Programming CoSc3053 38
Thread Synchronization Example
package MultiThreading;

public class TWithdraw extends Thread {


Account account;
int amount;

TWithdraw(Account y, int amount) {


this.account = y;
this.amount = amount; //new Thread(this).start();
}
public void run() {
synchronized (account) {
try {
sleep(2000);
} catch (InterruptedException e) {
System.out.println(e.getCause());
}
}
account.withdraw(amount);
}
}
Java Programming CoSc3053 39
Thread Synchronization Example
package MultiThreading;

public class SyncMain {

public static void main(String[] args) {


Account x = new Account();
x.balance = 0;
x.accountNo = 1010;

TDeposit t1 = new TDeposit(x, 500);


TWithdraw t2 = new TWithdraw(x, 500);
t1.start();
t2.start();
}

}
Output
500 is deposited
Account No: 1010 Balance: 500 is updated by 3
You cant withraw this 500 amount
Account No: 1010 Balance: 500 ss updated by 2
Java Programming CoSc3053 40
Thread Synchronization
 Concepts you have to understanding in Thread Synchronization
– Resource sharing - data , file, disk etc ….
– Critical section - part of code that access required resource
– Mutual exclusion – way of preventing simultaneous access
– Locking or mutex – lock and start using while the other waiting
– Semaphore – uses wait() and signal()
– Monitor
– Race condition
– Inter-Thread communications

Java Programming CoSc3053 41


Thread Synchronization
 Producer/Consumer Relationship without Synchronization
– Buffer
• Shared memory region
– Producer thread
• Calls produce method to add item to buffer
• Calls wait if consumer has not read last message in buffer
• Writes to empty buffer and calls notify for consumer
– Consumer thread
• Reads message from buffer
• Calls wait if buffer empty
– Synchronize threads to avoid corrupted data
Java Programming CoSc3053 42
Thread Synchronization

Java Programming CoSc3053 43


Thread Synchronization

Java Programming CoSc3053 44


Thread Synchronization

Java Programming CoSc3053 45


End of Chapter 5

Next: Networking in Java

https://docs.oracle.com/en/java/

Java Programming CoSc3053 49

You might also like