SlideShare a Scribd company logo
1 of 26
Multithreading
• 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.
• Java Multithreading is mostly used in games,
animation, etc.
• Advantages of Java Multithreading
1) It doesn't block the user because threads are
independent and thread 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.
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 (Multiprocessing)
2. Thread-based Multitasking (Multithreading)
2) Thread-based Multitasking (Multithreading)
• Threads share the same address space.
• A thread is lightweight.
• Cost of communication between the thread is
low.
Main Java Thread
Thread and Runnable interface to create and
manage threads, beginning with the main java
thread, that all Java programs have.
Why Is Main Thread So Important?
Because this thread affects the other 'child' threads
Because it performs various shutdown actions
It is created automatically when your program is
started.
How to Create a Java Thread?
1.Runnable Interface
• The easiest way to create a thread is to create a class
that implements the Runnable interface.
• To implement Runnable interface, a class need only
implement a single method called run( ), which is
declared like this:
public void run( )
public class MyClass implements Runnable {
public void run()
{
System.out.println("MyClass running");
}
}
To execute the run() method by a thread, pass an instance of
MyClass to a Thread in its constructor (A constructor in
Java is a block of code similar to a method that's called when
an instance of an object is created). Here is how that is done:
Thread t1 = new Thread(new MyClass ());
t1.start();
2. Extending Java Thread
The second way to create a thread is to create a
new class that extends Thread, then override the
run() method and then to create an instance of
that class. The run() method is what is executed by
the thread after you call start(). Here is an example
of creating a Java Thread subclass:
public class MyClass extends Thread {
public void run(){
System.out.println("MyClass running");
}
}
To create and start the above thread you can do
so like this:
MyClass t1 = new MyClass ();
T1.start();
When the run() method executes it will print out
the text " MyClass running ".
1) Process-based Multitasking (Multiprocessing)
• 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.
Method Signature Description
String getName() Retrieves the name of running thread in the current
context in String format
void start() This method will start a new thread of execution by
calling run() method of Thread/runnable object.
void run() This method is the entry point of the thread. Execution of
thread starts from this method.
void sleep(int
sleeptime)
This method suspend the thread for mentioned time
duration in argument (sleeptime in ms)
void yield() By invoking this method the current thread pause its
execution temporarily and allow other threads to execute.
void join() This method used to queue up a thread in execution.
Once called on thread, current thread will wait till calling
thread completes its execution
boolean isAlive() This method will check if thread is alive or dead
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.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread
3 constants defined in Thread class:
1.public static int MIN_PRIORITY
2.public static int NORM_PRIORITY
3.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.
Example of priority of a Thread:
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
Synchronization in Java
Synchronization in java 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.
Why use Synchronization ?
The synchronization is mainly used to
To prevent thread interference.
To prevent consistency problem.
Thread Synchronization
There are two types of thread synchronization mutual
exclusive and inter-thread communication.
1. Mutual Exclusive
i. Synchronized method.
ii. Synchronized block.
iii. static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with
one another while sharing data. This can be done by three
ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization
Concept of Lock in Java
Synchronization is built around an internal entity known as
the lock or monitor. Every object has an lock associated with
it. By convention, a thread that needs consistent access to an
object's fields has to acquire the object's lock before
accessing them, and then release the lock when it's done with
them.
Understanding the problem without Synchronization
In this example, there is no synchronization, so output is inconsistent.
class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output: 5
100
10
200
15
300
20
400
25
500
 Java synchronized method
• If you declare any method as synchronized, it is
known as synchronized method.
• Synchronized method is used to lock an object for any
shared resource.
• When a thread invokes a synchronized method, it
automatically acquires the lock for that object and
releases it when the thread completes its task.
//example of java synchronized method
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output: 5
10
15
20
25
100
200
300
400
500
Inter-thread communication in Java
Inter-thread communication or Co-operation is all about
allowing synchronized threads to communicate with each
other.
Cooperation (Inter-thread communication) is a
mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter (or
lock) in the same critical section to be executed.It is
implemented by following methods of Object class:
wait()
notify()
notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another
thread invokes the notify() method or the notifyAll() method for this
object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be
called from the synchronized method only otherwise it will throw
exception.
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any
threads are waiting on this object, one of them is chosen to be
awakened. The choice is arbitrary and occurs at the discretion of the
implementation. Syntax:
public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
public final void notifyAll()

More Related Content

Similar to 07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx

Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaMonika Mishra
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptxmadan r
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
Multithreading
MultithreadingMultithreading
Multithreadingsagsharma
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaArafat Hossan
 
BCA MultiThreading.ppt
BCA MultiThreading.pptBCA MultiThreading.ppt
BCA MultiThreading.pptsarthakgithub
 
Multithreadingppt.pptx
Multithreadingppt.pptxMultithreadingppt.pptx
Multithreadingppt.pptxHKShab
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreadingKuntal Bhowmick
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024nehakumari0xf
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024kashyapneha2809
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And MultithreadingShraddha
 

Similar to 07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx (20)

Multi threading
Multi threadingMulti threading
Multi threading
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Threading concepts
Threading conceptsThreading concepts
Threading concepts
 
Slide 7 Thread-1.pptx
Slide 7 Thread-1.pptxSlide 7 Thread-1.pptx
Slide 7 Thread-1.pptx
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
BCA MultiThreading.ppt
BCA MultiThreading.pptBCA MultiThreading.ppt
BCA MultiThreading.ppt
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
 
Multithreadingppt.pptx
Multithreadingppt.pptxMultithreadingppt.pptx
Multithreadingppt.pptx
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 

Recently uploaded

Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixingviprabot1
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIkoyaldeepu123
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 

Recently uploaded (20)

Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixing
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AI
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 

07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx

  • 1. Multithreading • 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. • Java Multithreading is mostly used in games, animation, etc.
  • 2. • Advantages of Java Multithreading 1) It doesn't block the user because threads are independent and thread 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.
  • 3. 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 (Multiprocessing) 2. Thread-based Multitasking (Multithreading)
  • 4. 2) Thread-based Multitasking (Multithreading) • Threads share the same address space. • A thread is lightweight. • Cost of communication between the thread is low.
  • 5. Main Java Thread Thread and Runnable interface to create and manage threads, beginning with the main java thread, that all Java programs have. Why Is Main Thread So Important? Because this thread affects the other 'child' threads Because it performs various shutdown actions It is created automatically when your program is started.
  • 6. How to Create a Java Thread? 1.Runnable Interface • The easiest way to create a thread is to create a class that implements the Runnable interface. • To implement Runnable interface, a class need only implement a single method called run( ), which is declared like this: public void run( )
  • 7. public class MyClass implements Runnable { public void run() { System.out.println("MyClass running"); } } To execute the run() method by a thread, pass an instance of MyClass to a Thread in its constructor (A constructor in Java is a block of code similar to a method that's called when an instance of an object is created). Here is how that is done:
  • 8. Thread t1 = new Thread(new MyClass ()); t1.start(); 2. Extending Java Thread The second way to create a thread is to create a new class that extends Thread, then override the run() method and then to create an instance of that class. The run() method is what is executed by the thread after you call start(). Here is an example of creating a Java Thread subclass:
  • 9. public class MyClass extends Thread { public void run(){ System.out.println("MyClass running"); } }
  • 10. To create and start the above thread you can do so like this: MyClass t1 = new MyClass (); T1.start(); When the run() method executes it will print out the text " MyClass running ".
  • 11. 1) Process-based Multitasking (Multiprocessing) • 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.
  • 12. Method Signature Description String getName() Retrieves the name of running thread in the current context in String format void start() This method will start a new thread of execution by calling run() method of Thread/runnable object. void run() This method is the entry point of the thread. Execution of thread starts from this method. void sleep(int sleeptime) This method suspend the thread for mentioned time duration in argument (sleeptime in ms) void yield() By invoking this method the current thread pause its execution temporarily and allow other threads to execute. void join() This method used to queue up a thread in execution. Once called on thread, current thread will wait till calling thread completes its execution boolean isAlive() This method will check if thread is alive or dead
  • 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. public int getPriority(): returns the priority of the thread. public int setPriority(int priority): changes the priority of the thread 3 constants defined in Thread class: 1.public static int MIN_PRIORITY 2.public static int NORM_PRIORITY 3.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.
  • 14. Example of priority of a Thread: class TestMultiPriority1 extends Thread{ public void run(){ System.out.println("running thread name is:"+Thread.currentThread().getName()); System.out.println("running thread priority is:"+Thread.currentThread().getPriority()); } public static void main(String args[]){ TestMultiPriority1 m1=new TestMultiPriority1(); TestMultiPriority1 m2=new TestMultiPriority1(); m1.setPriority(Thread.MIN_PRIORITY); m2.setPriority(Thread.MAX_PRIORITY); m1.start(); m2.start(); } } Output:running thread name is:Thread-0 running thread priority is:10 running thread name is:Thread-1 running thread priority is:1
  • 15. Synchronization in Java Synchronization in java 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. Why use Synchronization ? The synchronization is mainly used to To prevent thread interference. To prevent consistency problem.
  • 16. Thread Synchronization There are two types of thread synchronization mutual exclusive and inter-thread communication. 1. Mutual Exclusive i. Synchronized method. ii. Synchronized block. iii. static synchronization. 2. Cooperation (Inter-thread communication in java)
  • 17. Mutual Exclusive Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be done by three ways in java: 1. by synchronized method 2. by synchronized block 3. by static synchronization Concept of Lock in Java Synchronization is built around an internal entity known as the lock or monitor. Every object has an lock associated with it. By convention, a thread that needs consistent access to an object's fields has to acquire the object's lock before accessing them, and then release the lock when it's done with them.
  • 18. Understanding the problem without Synchronization In this example, there is no synchronization, so output is inconsistent. class Table{ void printTable(int n){//method not synchronized for(int i=1;i<=5;i++){ System.out.println(n*i); try{ Thread.sleep(400); }catch(Exception e){System.out.println(e);} } } } class MyThread1 extends Thread{ Table t; MyThread1(Table t){ this.t=t; } public void run(){ t.printTable(5); } }
  • 19. class MyThread2 extends Thread{ Table t; MyThread2(Table t){ this.t=t; } public void run(){ t.printTable(100); } } class TestSynchronization1{ public static void main(String args[]){ Table obj = new Table();//only one object MyThread1 t1=new MyThread1(obj); MyThread2 t2=new MyThread2(obj); t1.start(); t2.start(); } }
  • 21.  Java synchronized method • If you declare any method as synchronized, it is known as synchronized method. • Synchronized method is used to lock an object for any shared resource. • When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task.
  • 22. //example of java synchronized method class Table{ synchronized void printTable(int n){//synchronized method for(int i=1;i<=5;i++){ System.out.println(n*i); try{ Thread.sleep(400); }catch(Exception e){System.out.println(e);} } } } class MyThread1 extends Thread{ Table t; MyThread1(Table t){ this.t=t; } public void run(){ t.printTable(5); } }
  • 23. class MyThread2 extends Thread{ Table t; MyThread2(Table t){ this.t=t; } public void run(){ t.printTable(100); } } public class TestSynchronization2{ public static void main(String args[]){ Table obj = new Table();//only one object MyThread1 t1=new MyThread1(obj); MyThread2 t2=new MyThread2(obj); t1.start(); t2.start(); } }
  • 25. Inter-thread communication in Java Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other. Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of Object class: wait() notify() notifyAll()
  • 26. 1) wait() method Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. The current thread must own this object's monitor, so it must be called from the synchronized method only otherwise it will throw exception. 2) notify() method Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. Syntax: public final void notify() 3) notifyAll() method Wakes up all threads that are waiting on this object's monitor. Syntax: public final void notifyAll()