0% found this document useful (0 votes)
13 views

Chapter 3 ( MultiThreading )

Chapter Three discusses multithreading in Java, which allows multiple threads to execute simultaneously, enhancing multitasking capabilities. It explains the differences between process-based and thread-based multitasking, the lifecycle of threads, and methods for creating and managing threads. Additionally, it covers the advantages of multithreading, including improved performance and resource utilization.

Uploaded by

eshetufeleke21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Chapter 3 ( MultiThreading )

Chapter Three discusses multithreading in Java, which allows multiple threads to execute simultaneously, enhancing multitasking capabilities. It explains the differences between process-based and thread-based multitasking, the lifecycle of threads, and methods for creating and managing threads. Additionally, it covers the advantages of multithreading, including improved performance and resource utilization.

Uploaded by

eshetufeleke21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

CHAPTER THREE

MULTI THREADING

By: Behayilu M.
Faculty of Computing and Software Engineering(FCSE),
Arba Minch Institute of Technology(AMiT),
Arba Minch University
Introduction
• Multithreading in java is a process of executing multiple threads simultaneously. Or in other words,

• Multithreading enables multiple tasks in a program to be executed concurrently.

• Multiprocessor: refers to the use of two or more central processing units (CPU) within a single
computer system.

• Multiprocessing and multithreading, both are used to achieve multitasking.


• Java Multithreading is mostly used in games, animation, etc.

• Multitasking is when multiple processes share common processing resources such as a CPU.

• Multi-threading extends the idea of multitasking into applications where you can subdivide specific
operations within a single application into individual threads.
• Each of the threads can run in parallel.
2
Multitasking
• Multitasking is a process of executing multiple tasks simultaneously.
• We use multitasking to utilize the CPU.
• Multitasking can be achieved in two ways:
1. Process-based Multitasking (Multi processing)
2. Thread-based Multitasking (Multi threading)
1. Process-based Multitasking (Multi processing)
– Each process has an address in memory. In other words, each process allocates a separate
memory area.
– A process is heavyweight.
– Cost of communication between the process is high.
– Switching from one process to another requires some time for saving and loading registers,
memory maps, updating lists, etc.
2. Thread-based Multitasking (Multithreading)
– Threads share the same address space.
– A thread is lightweight.
– Cost of communication between the thread is low.
3
Multitasking
What is Thread in Java?
• A thread is a lightweight sub-process, the smallest unit of processing.
• It is a separate path of execution.

• Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads.
• It uses a shared memory area.

• Thread: single sequential flow of control within a program


• Single-threaded program can handle one task at any time.

• Multitasking allows single processor to run several concurrent threads.


• Most modern operating systems support multitasking.
…cont’d

• 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 thread provides the mechanism for running a task.

• With Java, you can launch multiple threads from a program


concurrently.

• These threads can be executed simultaneously in multiprocessor


systems, as shown in Figure below.
…cont’d

Multiple threads are


running on multiple CPUs

Multiple threads sharing a


single CPU
Process Thread
Process is a program in execution. A thread is a subset (part) of the process.

A process consists of multiple threads. A thread is a smallest part of the process that can
execute concurrently with other parts (threads) of the
process.

A process is a heavyweight program A thread is a lightweight program.

A process has its own address space. A thread uses the process’s address space and
shares it with the other threads of that process.

A process can communicate with other A thread can communicate with other thread (of the
process by using inter- process same process) directly by using methods like wait(),
communication. notify(), notifyAll().
5
…cont’d

T1
T2

Process 2
T1
T3
T2
process 1 T1

Process 3

os
 As shown in the above figure, a thread is executed inside the process. There is context-switching between
the threads.
 There can be multiple processes inside the OS, and one process can have multiple threads.
Note: At a time one thread is executed only.
Advantages of Multithreading
• You can perform multiple operations together at a time, so it saves time.

• Threads are independent, so it doesn't affect other threads if an exception occurs in a


single thread.
• Server can handle multiple clients simultaneously
• It is used to perform tasks in parallel processing
• CPU should not remain idle.

• A thread can execute concurrently with other threads within a single process.

• All threads managed by the JVM share memory space and can communicate with each
other.
1
0
11
Main Thread in Java
• When we start any java program, one thread begins running immediately, which is called
Main thread of that program.
• The main thread is created automatically when your program is started.
• Main thread is the last thread to be executed in a program.
• When main thread finishes the execution, the program terminates immediately.
public class MainThread
{
public static void main(String[] args)
{
System.out.println(Thread.currentThread()); //main // or
Thread obj = Thread.currentThread();
System.out.println("Name of current thread is " +obj.getName()); //main
}
}
12
The Thread class in Java
• Java provides Thread class to achieve thread programming.
• Thread class provides constructors and methods to create and perform operations
on a thread.
• Threads can be created by using two mechanisms :
1. Extending java.lang.Thread class
 The thread class extends the Thread class
 run() method must be overridden
 run() is called when execution of the thread begins
 A thread terminates when run() returns
 start() method invokes run()
 Calling run() does not create a new thread
2. Implementing java.lang.Runnable interface
 Thread class implements Runnable interface.
 Runnable interface have only one method named: public void run():
is used to perform action for a thread.
 You need to implement a run() method provided the Runnable
interface
13

1. Creating a Thread by implementing Runnable Interface

• We create a new class which implements Runnable interface and override run() method.
• Then we instantiate a Thread object and call start() method on this object.

java.lang.Runnable TaskClass // Client class


public class Client
{
// Custom task ...
public
class class TaskClass implements Runnable public void
{ someMethod() {
public TaskClass(...)
... ...
TaskClass task = new
{ .. // Create an
TaskClass(...);
}. // Createof
instance a
Thread
thread thread = new
TaskClass
Thread(taskClass);
public
// void run()
Implement { method in Runnable
the run // Start a
// Tell system how to run custom thread.start()
thread
thread .
;.
} ... }.
.. ..
}. }.
14

Example: Creating and Launching Threads using the Runnable


Interface

• The program in the next slide creates/performs three tasks and


runs three threads:

▫ The first thread prints the letter a 100 times.

▫ The second thread prints the letter b 100 times.

▫ The third thread prints the integers 1 through 100.


15

Example: Using the Runnable Interface


class PrintChar implements Runnable {
private char charToPrint;
private int times;
public PrintChar(char c, int t) {
charToPrint = c;
times = t;
}
public void run() {
for (int i = 0; i < times; i++) {
System.out.print(charToPrint);
}
}
}
class PrintNum implements Runnable{
private int lastNum;
public PrintNum(int n) {
lastNum = n;
}
public void run() {
for (int i = 1; i <=
lastNum; i++) {
System.out.print(" " +
i);
}
}
16

Example: Using the Runnable Interface

public class TaskThreadDemo {


public static void main(String[] args) {
// Create tasks
Runnable printA = new PrintChar('a' , 100);
Runnable printB = new PrintChar('b' ,
100); Runnable print100 = new
PrintNum(100);
// Create threads
Thread thread1 = new Thread(printA);
Thread thread2 = new Thread(printB);
Thread thread3 = new Thread(print100);
// Start threads
thread1.start();
thread2.start();
thread3.start();
}
}
17
Code Description
• The program creates three tasks .
• To run them concurrently, three threads are created.
• The start() method is invoked to start a thread that causes the run() method in the task to be
executed.
• When the run() method completes, the thread terminates.
• Because the first two tasks, printA and printB, have similar functionality, they can
be defined in one task class PrintChar.
• The PrintCharclass implementsRunnable and overrides the run()
method with the print-character action.
• This class provides a frameworkfor printing any single character a given number of
times.
• The runnable objects printA and printB are instances of the PrintChar class.
• The PrintNumclass implementsRunnable and overrides the run()
method with the print-number action.
• This class provides a framework for printing numbers from 1 to n, for any integer n. The
runnable object print100 is an instance of the class printNum class.
18

2. Creating a Thread by extending Thread class

• We create a class that extends the java.lang.Thread class.

• This class overrides the run() method available in the Thread class.
• A thread begins its life inside run() method.

• We create an object of our new class and call start() method to start the
execution of a thread.

• Start() invokes the run() method on the Thread object.


2. Creating a Thread by extending Thread class
• The Thread class contains the constructors for creating
threads for tasks and the methods for controlling threads.
2. Creating a Thread by extending Thread class

20
Life Cycle of a Thread (Thread States)
• A thread state indicates the status of thread.
• Tasks are executed in threads.
• A thread can be in one of five states: New, Ready/Runnable, Running, Blocked,
or Finished/Terminated.
• The life cycle of the thread in java is controlled by JVM.
22

Life Cycle of a Thread (Thread States)


1. New : When a thread is newly created, it enters the New state.
• A thread begins its life cycle in the new state.
2. Runnable : After a thread is started by calling its start() method, it enters the
Ready/Runnable state.
• A ready thread is runnable but may not be running yet.
• The operating system has to allocate CPU time to it
3. Running : When a ready thread begins executing, it enters the Running state.
• A method is running thread if the thread scheduler has selected it.
• A running thread can enter the Ready state if its given CPU time expires or its
yield() method is called.
• It may have invoked the join() , sleep() , or wait() method.
• It may be waiting for an I/O operation to finish.
23

Life Cycle of a Thread (Thread States)

4. Waiting : a thread is waiting for another thread to perform a task.


• In this stage the thread is still alive.

5.Terminated : Finally, a thread is Finished if it completes the execution of its


run() method.
 Or when it complete its task.
Thread methods

1. the static Yiled ( ) method


 A yield() method is a static method of Thread class and it can stop the
currently executing thread and will give a chance to other waiting threads of the
same priority.
 You can use the yield() method to temporarily release time for other threads.
 Thread.yield( );
Yield( ) Example
class ThreadExample extends Thread {
public void run() {
for (int i = 0; i <2; ++i) {
Thread.yield();
System.out.println("Thread started:" + Thread.currentThread().getName());
}
System.out.println("Thread ended:" + Thread.currentThread().getName());
}}
public class ThreadYiledExample output
{
public static void main(String[] args) Thread started:main
{
ThreadExample thread = new ThreadExample();
Thread started:Thread-0
thread.start(); Thread started:main
for (int i = 0; i < 2; ++i)
{ Thread started:Thread-0
System.out.println("Thread started:" + Thread.currentThread().getName());
Thread ended:main
}
System.out.println("Thread ended:" + Thread.currentThread().getName()); Thread ended:Thread-0
}
}
Thread Methods

2. The static sleep(milliseconds) method


 The sleep(long milliseconds) method of Thread class is used to sleep a thread
for the specified amount of time.
sleep( ) Example
public class ThreadSleepExample1 extends Thread {
public void run() {
for (int i = 0; i <=2; i++) {
System.out.println(Thread.currentThread().getName()+ " " + i);
try {
// thread to sleep for 1000 milliseconds
Thread.sleep(1000); output
} catch (Exception e) {
System.out.println(e); Thread-1 0
}
Thread-0 0
}
Thread-0 1
}
public static void main(String[] args) throws Exception { Thread-1 1
ThreadSleepExample1 t1=new ThreadSleepExample1(); Thread-1 2
t1.start(); Thread-0 2
ThreadSleepExample1 t2=new ThreadSleepExample1();
t2.start();
}
}
Thread methods

3.The static isAlive ( ) method


 The isAlive() method of thread class tests if the thread is alive.

 A thread is considered alive when the start() method of thread class has been
called and the thread is not yet dead.
 This method returns true if the thread is still running and not finished.
isAlive( ) Example
public class ThreadIsAliveExample extends Thread
{
public void run() {
try {
Thread.sleep(300);
System.out.println("is run() method isAlive: "+Thread.currentThread().isAlive());
} catch (InterruptedException ie) { }
}
output

public static void main(String[] args)


before starting thread isAlive: false
{
ThreadIsAliveExample t1 = new ThreadIsAliveExample(); after starting thread isAlive: true
System.out.println("before starting thread isAlive: " + t1.isAlive()); is run() method isAlive: true
t1.start();
System.out.println("after starting thread isAlive: " + t1.isAlive());
}
}
Thread Methods

4. The static join ( ) method


 Join method in Java allows one thread to wait until another thread completes its execution.

 In simpler words, it means it waits for the other thread to die.

 It has a void type and throws InterruptedException.

 Joining threads in Java has three functions namely,

• join()

• join(long millis)

• join(long millis, int nanos)


Join Example
public class ThreadJoinexample2 extends Thread {
public void run(){
for(int i=1;i<=4;i++){
output
try{
Thread.sleep(500); 1
}catch(Exception e){System.out.println(e);}
2
System.out.println(i);
} }
3
public static void main(String args[]){ 4
ThreadJoinexample2 th1=new ThreadJoinexample2 (); 1
ThreadJoinexample2 th2=new ThreadJoinexample2 (); 1
ThreadJoinexample2 th3=new ThreadJoinexample2 (); 2
th1.start();
2
try{
th1.join();
3
} 3
catch(Exception e){ System.out.println(e); } 4
th2.start(); 4
th3.start();
}
The join() Method
• You can use the join() method to force one thread to wait for another thread to finish.
public class MyThread extends Thread{
Public void run( ){
System.out.println(“r1”);
try{
Thread.sleep(500);
}catch(InterruptedException e){}
System.out.println(“r2”);
} output
public static void main(String args[]){
MyThread t1=new MyThread( );
r1
MyThread t2=new MyThread();
t1.start( ); r2
try{ r1
t1.join( ); //waiting for t1 to finish
r2
} catch(InterruptedException e){}
t2.srart( );
}
Thread Priority
• Each thread have a priority. Priorities are represented by numbers ranging from 1 and 10.
• You can increase or decrease the priority of any thread by using the setPriority method, and you can
get the thread’s priority by using the getPriority method.
• The Thread class has three int constant priorities.
– public static int MIN_PRIORITY --- with value 1
– public static int NORM_PRIORITY --- with value 5 t1.setPriority(MAX_PRIORITY); or
t1.setPriority(10);
– public static int MAX_PRIORITY --- with value 10
• Default priority of a thread is 5 (NORM_PRIORITY).
• The JVM always picks the currently runnable thread with the highest priority.
• A lower priority thread can run only when no higher-priority threads are running.
• If all runnable threads have equal priorities, each is assigned an equal portion of the CPU time in a
circular queue. This is called round-robin scheduling.
• You can reset the priority using setPriority(int priority).

27
34
Thread Scheduling in Java
• Anoperating system’s thread scheduler determines which thread runs next.
• Most operating systems use time slicing for threads of equal priority.

• Thread scheduler in java is the part of the JVM that decides which thread should run.

• There is no guarantee that which runnable thread will be chosen to run by the thread scheduler.

• Only one thread at a time can run in a single process.

• The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.

• Preemptive scheduling: the highest priority task executes until it enters a higher priority task comes
into existence.
• when a thread of higher priority enters the running state, it preempts the current thread.

• Time slicing: a task executes for a predefined slice of time and then reenters the pool of ready tasks.
35

Thread Scheduling in Java

• Starvation: Higher-priority threads can postpone (possible forever) the execution


of lower-priority threads.
• A thread may never get a chance to run if there is always a higher-priority thread
running or a same-priority thread that never yields.
• This situation is known as contention or starvation.
• To avoid contention, the thread with higher priority must periodically invoke the
sleep or yield method to give a thread with a lower or the same priority a chance
to run.
Thread Synchronization
• Thread Synchronization is the capability to control the access of multiple
threads to any shared resource.
• Java Synchronization is better option where we want to allow only one thread to
access the shared resource.
• A shared resource may be corrupted if it is accessed simultaneously by multiple
threads.
• Example: two unsynchronized threads accessing the same bank account may
cause conflict. Task 1 and Task 2 both add 1 to the same balance
37
The synchronized Keyword
• Problem: race conditions

• Solution: give exclusive access to one thread at a time to code that manipulates a
shared object.
• To avoid race conditions, it is necessary to prevent more than one thread from
simultaneously entering a certain part of the program, known as the critical region.
• Synchronization keeps other threads waiting until the object is available.

• The synchronized keyword synchronizes the method so that only one thread can access
the method at a time.
…cont’d

• Synchronization is implemented using the concept called monitors.

 Each object in Java is associated with a monitor, which a thread can lock or unlock.

 Only one thread at a time may hold a lock on a monitor.

• Synchronization in Java can be achieved in two different ways:

1. Using synchronized methods.

2. Using synchronized blocks.

3. Static synchronization
1. Using synchronized methods
 Prefix the keyword synchronized to the shared resource which needs to be synchronized.

 The resource can be a method, variable or any other program elements.

 Here shared resource is the ‘count( )’ method.

 Following is the general form of the synchronized statement:

• synchronized(objectidentifier)

{
// Access shared variables and other shared resources
}

• Here, the objectidentifier is a reference to an object whose lock associates with the monitor
that the synchronized statement represents.
Using synchronized methods
class Counter{
int count;
public void run() {
public synchronized void increment() { for(int i=1;i<=1000;i++) {
count++; y.increment();
} }
} }
class CounterA extends Thread{
}
public class SynchronizationExample2 {
Counter x;
public static void main(String args[])throws Exception
public CounterA(Counter ob1){ {
this.x=ob1; Counter c=new Counter();
} CounterA t1=new CounterA(c);
public void run() { CounterB t2=new CounterB(c);
t1.start();
for(int i=1;i<=1000;i++) {
t2.start();
x.increment(); //c.join(); this join method must be called otherwise main thread
} is doing nothing and just printing count
} t1.join();
} t2.join();
class CounterB extends Thread{
System.out.println("count = "+c.count);
}
Counter y;
}
public CounterB(Counter ob2)
{
this.y=ob2;
≈//≈

You might also like