0% found this document useful (0 votes)
3 views20 pages

Chapter 2 Multithreading

Chapter 2 discusses multithreading in Java, explaining that it allows multiple threads to execute simultaneously, which is more memory-efficient than multiprocessing. It covers the advantages of multithreading, the lifecycle of a thread, how to create threads using both the Thread class and the Runnable interface, and the importance of synchronization and inter-thread communication. Additionally, it highlights thread priorities and provides examples of thread creation and synchronization in Java.

Uploaded by

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

Chapter 2 Multithreading

Chapter 2 discusses multithreading in Java, explaining that it allows multiple threads to execute simultaneously, which is more memory-efficient than multiprocessing. It covers the advantages of multithreading, the lifecycle of a thread, how to create threads using both the Thread class and the Runnable interface, and the importance of synchronization and inter-thread communication. Additionally, it highlights thread priorities and provides examples of thread creation and synchronization in Java.

Uploaded by

sakshimane4199
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 2

Multithreading

Shravani D. Pawar 1
Multithreading in Java
• Multithreading in Java is a process of executing multiple threads
simultaneously.
• A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve
multitasking.
• However, we use multithreading than multiprocessing because threads
use a shared memory area. They don't allocate separate memory area
so saves memory, and context-switching between the threads takes
less time than process.

Shravani D. Pawar 2
Advantages of Java
Multithreading
1) It doesn't block the user because threads are independent and you
can perform multiple operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an
exception occurs in a single thread.

Shravani D. Pawar 3
What is Thread in java
• A thread is a lightweight subprocess, the smallest unit of processing. It
is a separate path of execution.
• Threads are independent. If there occurs an exception in one thread, it
doesn't affect other threads. It uses a shared memory area.

Shravani D. Pawar 4
Life cycle of a Thread

Shravani D. Pawar 5
The life cycle of the thread in java is controlled by JVM. The
java thread states are as follows:
1) New: The thread is in new state if you create an instance of Thread class
but before the invocation of start() method.
2) Runnable: The thread is in runnable state after invocation of start()
method, but the thread scheduler has not selected it to be the running
thread.
3) Running: The thread is in running state if the thread scheduler has
selected it.
4) Non-Runnable (Blocked): This is the state when the thread is still alive,
but is currently not eligible to run.
5) Terminated: A thread is in terminated or dead state when its run()
method exits.

Shravani D. Pawar 6
Creating thread

Shravani D. Pawar 7
Using a Thread class:
• public void run(): is used to perform action for a thread.
• public void start(): starts the execution of the [Link] calls the run()
method on the thread.
• public void sleep(long miliseconds): Causes the currently executing thread
to sleep (temporarily cease execution) for the specified number of
milliseconds
• public Thread currentThread(): returns the reference of currently executing
thread.
• public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
• public void suspend(): is used to suspend the thread(depricated).
• public boolean isDaemon(): tests if the thread is a daemon thread.
• public void interrupt(): interrupts the thread.

Shravani D. Pawar 8
Java Thread Example by extending Thread class
class Multi extends Thread {
public void run() {
[Link]("thread is running...");
}
public static void main(String args[]) {
Multi t1=new Multi();
[Link]();
}
}
Output:thread is running...

Shravani D. Pawar 9
Main Thread
• Every Java program has always at least one thread, even if you do not create
any thread. This thread is called main thread in Java. The main thread is
also called parent thread and the rest of threads that are generated from it
are called child threads of the program.
• Main thread is the last thread to be executed in a program. When the main
thread finishes the execution, the program terminates immediately.
Whenever Java program starts, the main thread is created automatically.

Shravani D. Pawar 10
Let’s create a Java program to find the thread used by JVM to
execute statements and display the name of main thread.
public class MainThread {
public static void main(String[] args)
{
// Create a Thread object by calling currentThread() method of class Thread.
Thread obj = [Link]();

[Link]("Current thread is " +obj); // line 7


[Link]("Name of current thread is " +[Link]());
}
}
Output: Current thread is Thread[main, 5, main]
Name of current thread is main

Shravani D. Pawar 11
Using Runnable interface
• The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread. Runnable interface
have only one method named run().
• void run(): is used to perform action for a thread.
• start() method of Thread class is used to start a newly created thread.

Shravani D. Pawar 12
Java Thread Example by implementing Runnable
interface
class Multi implements Runnable {
public void run() {
[Link]("thread is running...");
}
public static void main(String args[]) {
Multi m1=new Multi();
Thread t1 =new Thread(m1);
[Link]();
}
}
Output:thread is running...

Shravani D. Pawar 13
Thread priority:
• Each thread have a priority. Priorities are represented by a number
between 1 and 10. In most cases, thread schedular schedules the
threads according to their priority (known as preemptive scheduling).
But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses.
• 3 constants defined in Thread class:
• public static int MIN_PRIORITY
• public static int NORM_PRIORITY
• public static int MAX_PRIORITY
• Default priority of a thread is 5 (NORM_PRIORITY). The value of
MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.

Shravani D. Pawar 14
Synchronization
• When two or more threads wants to access a shared, then it must
ensure that the resource will be used by only one thread at an instant of
time. The mechanism of this process is called synchronization.
• Synchronization is a process of controlling the access of shared
resources by the multiple threads in such a manner that only one
thread can access a particular resource at a time.

Shravani D. Pawar 15
Program for Synchronization
class mythread extends Thread {
String msg[] = {"Java", "Supports", "Multithreading", "Concept"};
mythread(String name) {
super(name);
}
public void run() {
display(getName());
[Link]("Exit from "+getName());
}
synchronized void display(String name) //Synchronized method {
for(int i=0; i<[Link]; i++) {
[Link](name+msg[i]);
}
}
}

Shravani D. Pawar 16
Output:

Main thread exited


/* Main class */
class MySynchro { Thread 1: Java
public static void main(String[] args) { Thread 2: Java
mythread t1 = new mythread("Thread 1: ");
mythread t2 = new mythread("Thread 2: "); Thread 1: Supports
[Link](); Thread 1: Multithreading
[Link]();
Thread 1: Concept
[Link]("Main thread exited");
} Thread 2: Supports
}
Thread 2: Multithreading

Thread 2: Concept

Exit from Thread 1:

Exit from Thread 2:

Shravani D. Pawar 17
Inter-Thread Communication
• Inter-thread communication or Co-operation is all about allowing
synchronized threads to communicate with each other.
• It is implemented by following methods of Object class:
• wait()
• notify()
• notifyAll()

Shravani D. Pawar 18
Shravani D. Pawar 19
Shravani D. Pawar 20

You might also like