Chapter 3 ( MultiThreading )
Chapter 3 ( MultiThreading )
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,
• Multiprocessor: refers to the use of two or more central processing units (CPU) within a single
computer system.
• 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.
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 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.
• 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
• 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.
• 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.
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
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
• join()
• join(long millis)
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.
• 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
• 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
Each object in Java is associated with a monitor, which a thread can lock or unlock.
3. Static synchronization
1. Using synchronized methods
Prefix the keyword synchronized to the shared resource which needs to be synchronized.
• 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;
≈//≈