SlideShare a Scribd company logo
1 of 37
Multithreading in Java
N.JUNNUBABU ASST PROF.,
Introduction
 The program in execution is called "Process".
 The program can be structured as set of individual units that can run in parallel. These
units can be called as "Threads". Multiprogramming is actually a kind of multitasking.
 The multitasking is either process-based or thread base.
 Process-based multitasking is nothing but, execution of more than one program
concurrently.
 Thread-based multitasking allows more than one thread within the program run
simultaneously or concurrently.
 The process is a Heavy Weight Process. The Thread is a Light Weight Process.
 The context-switching of CPU from one process to other requires more overhead as it
different address spaces are involved in it.
 On the other hand, context-switching is less overhead because of all the threads within the
same program.
 The objective of all forms of the Multitasking including the multithreading is to utilize the
idle time of the processor.
 From here onwards, thread-based multitasking is called "Multithreading".
Multithreading in Java.
 MULTITHREADING in Java is a process of executing two or more threads simultaneously to
maximum utilization of CPU. Multithreaded applications execute two or more threads run
concurrently. Hence, it is also known as Concurrency in Java. Each thread runs parallel to
each other. Mulitple threads don't allocate separate memory area, hence they save
memory. Also, context switching between threads takes less time.
 Advantages of 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.
Multithreading in Java.
 Every program that we have been writing has at least one thread, that is, the
"main" thread.
 Whenever a program starts executing, the JVM is responsible for creating the
main thread and calling "main()" method. Along with this main thread, some
other threads are also running to carryout the tasks such as "finalization" and
"garbage collection". The thread can either die naturally or be forced to die.
 Thread dies naturally when it exits from the "run()" method.
 Thread can be forced to die by calling "interrupt()" method.
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)
 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.
Difference between Multiprocessing and
Multithreading
Process-Based Multitasking Thread-Based Multitasking
This deals with "Big Picture" This deals with Details
These are Heavyweight tasks These are Lightweight tasks
Inter-process communication is
expensive and limited
Inter-Thread communication is
inexpensive.
Context switching from one process
to another is costly in terms of
memory
Context switching is low cost in terms
of memory, because they run on the
same address space
This is not under the control of Java This is controlled by Java
Life Cycle of a Thread
 During the life time of the thread, there are many states it can enter.The life cycle
of the thread in java is controlled by JVM.
The java thread states are as follows:
 Newborn state(New state or start state)
The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
 At this state we can do the following:
1. Schedule it for running using the start() method.
2. Kill it using stop() method.
 Runnable State:
 A runnable state means that a thread is ready for execution and waiting for the availability of
the processor.
 That is the thread has joined the queue of the threads for execution.
 If all the threads have equal priority, then they are given time slots for execution in the round
rabin fashion, first-come first-serve manner.
 The thread that relinquishes the control will join the queue at the end and again waits for its
turn. This is known as time slicing.
 Running state:
Running state means that the processor has given its time to the thread for it execution.
The thread runs until it relinquishes the control or it is preempted by the other higher priority
thread. As shown in the fig. a running thread can be preempted using the suspend(), or wait(), or
sleep() methods.
 Blocked state:
A thread is said to be in the blocked state when it is prevented from entering into runnable state
and subsequently the running state.
 Dead state:
Every thread has a life cycle. A running thread ends its life when it has completed execution. It is a
natural death. However we also can kill the thread by sending the stop() message to it at any time.
How to create thread(java.lang.Thread package)
 There are two ways to create a thread:
 By extending Thread class
 By implementing Runnable interface.
 Creation of Thread in java is very simple task. There is a class called "Thread", which belongs
to the "java.lang.Thread" package.
 This package contains one interface also called "Runnable". Both these contain a common
method called "run()" which is the heart of the thread.
 The run() methods would have the following syntax:
Syntax:
public void run()
{
//statement for implementing the thread.
}
The methods of the Thread class are as follow:
 public void run(): is used to perform action for a thread.
 public void start(): starts the execution of the thread. JVM 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 void join(): waits for a thread to die.
 public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
 public int getPriority(): returns the priority of the thread.
 public int setPriority(int priority): changes the priority of the thread.
 public String getName(): returns the name of the thread.
 public void setName(String name): changes the name of the thread.
 public Thread currentThread(): returns the reference of currently executing
 public int getId(): returns the id of the thread.
 public Thread.State getState(): returns the state of the thread.
 public boolean isAlive(): tests if the thread is alive.
 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 void resume(): is used to resume the suspended thread(depricated).
 public void stop(): is used to stop the thread(depricated).
 public boolean isDaemon(): tests if the thread is a daemon thread.
 public void setDaemon(boolean b): marks the thread as daemon or user thread.
 public void interrupt(): interrupts the thread.
 public boolean isInterrupted(): tests if the thread has been interrupted.
 public static boolean interrupted(): tests if the current thread has been interrupted.
 notif()- is calls the thread that is waiting for resource
 notifyAll()-is calls the all threads that are waiting for resource
Thread Constructors
 Thread class:
 Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
 Commonly used Constructors of Thread class:
 Thread ()-without arguments, default constructor
 Thread(String str)- Thread contains name given as argument
 Thread(Thread obj, String str) -takes thread object and string
 Thread(class Obj) – takes the runnable class as target object
Thread class:
The Main Thread
 Every java program has a thread called "main" thread.
 When the program execution starts, the JVM creates "main" Thread and calls the
"main()" method from within that thread.
 Along with this JVM also creates other threads for the purpose of the
Housekeeping task such as "garbage" collection.
 The "main" thread Spawns the other Threads. These spawned threads are called
"Child Threads".
 The main thread is always is the last thread to finish execution.
 We, as Programmer can also take control of the main thread, using the method
"currentThread()".
 The main thread can be controlled by this method. We can also change the name
of the Thread using the method "setName(String name)".
Example Program.
class MainThread
{
public static void main(String args[])
{
Thread t=Thread.currentThread();
System.out.println("Name of the Thread is:"+t);
t.setName(“AIMS ECE 2nd YEAR STUDENTS");
System.out.println("Name of the Thread is:"+t);
}
}
The Thread Priorities
 To set a thread’s priority, use the setPriority( ) method, which is a member of Thread.
 This is its general form:
 final void setPriority(int level)
 Here, level specifies the new priority setting for the calling thread. The value of level must
be within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1
and 10, respectively. To return a thread to default priority, specify NORM_PRIORITY,
which is currently 5. These priorities are defined as static final variables within Thread.
 You can obtain the current priority setting by calling the getPriority( ) method of Thread,
shown here:
 final int getPriority( )
setPriority() and getpriority() method using.
 class PTest
{
public static void main(String args[])
{
//setting the priorities to the thread using the setPriority() method
PThread1 pt1=new PThread1();
pt1.setPriority(1);
PThread2 pt2=new PThread2();
pt2.setPriority(9);
PThread3 pt3=new PThread3();
pt3.setPriority(6);
pt1.start();
pt2.start();
pt3.start();
 //getting the priority
 System.out.println("The pt1 thread priority is :"+pt1.getPriority());
}
}
Runnable interface in Java
 Runnable interface in Java:
 The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. The class must define a method of no arguments called run .
This interface is designed to provide a common protocol for objects that wish to execute code
while they are active.
 Syntax:
 public void run()
 Steps involve in the Runnable interface in java:
1. Create a Runnable implementer and implement run() method.
2. Instantiate Thread class and pass the implementer to the Thread , Thread has a constructor
which accepts Runnable instance.
3. Invoke start() of Thread instance, start internally calls run() of the implementer.
Implementing Runnable Interface
package aims;
public class aimsRunnableDemo {
public static void main(String[] args) {
System.out.println("From main() : " + Thread.currentThread().getName());
System.out.println("Creating Runnable Instance...");
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("From run() : " + Thread.currentThread().getName());
}
};
System.out.println("Creating a Thread Instance...");
Thread thread = new Thread(runnable);
System.out.println("Launching a Thread...");
thread.start();
}
}
Output:-
From main() : main
Creating Runnable Instance...
Creating a Thread Instance...
Launching a Thread...
From run() : Thread-0
Synchronization in Java.
 When two or more threads need access to a shared resource, they need some way to
ensure that the resource will be used by only one thread at a time. The process by which
this is achieved is called synchronization.
 Key to synchronization is the concept of the monitor (also called a semaphore).
 A monitor is an object that is used as a mutually exclusive lock, or mutex.
 Only one thread can own a monitor at a given time. When a thread acquires a lock, it is
said to have entered the monitor.
 All other threads attempting to enter the locked monitor will be suspended until the first
thread exits the monitor.
 These other threads are said to be waiting for the monitor.
 A thread that owns a monitor can reenter the same monitor if it so desires.
Types of Synchronization:
 There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
 Process Synchronization
On the basis of synchronization, processes are categorized as one of the following two types:
1. Independent Process : Execution of one process does not affects the execution of other
processes.
2. Cooperative Process : Execution of one process affects the execution of other processes.
Process synchronization problem arises in the case of Cooperative process also because
resources are shared in Cooperative processes.
Types of Synchronization in Java.
Thread Synchronization.
 Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1.Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data.
This can be done by three ways in java:
 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. 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.
Synchronized method.
 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:-
public class SynchronizedCounter{
private int c = 0;
public synchronized void increment() {
c++;
}
public synchronized void decrement() {
c--;
}
public synchronized int value() {
return c;
} }
Synchronized block.
 Synchronized block.
Synchronized block can be used to perform synchronization on any specific resource of the method.
 Syntax:-
synchronized (object reference expression) {
//code block
}
 Points to remember for Synchronized block
Synchronized block is used to lock an object for any shared resource.
Scope of synchronized block is smaller than the method.
static synchronization.
 static synchronization.
If you make any static method as synchronized, the lock will be on the class not on object.
Problem without static synchronization:
Suppose there are two objects of a shared class(e.g. Table)named
object1 and object2.In case of synchronized method and synchronized
block there cannot be interference betweent1 and t2 or t3 and t4
because t1 and t2 both refers to a common object that have a single
lock.But there can be interference between t1 and t3 or t2 and t4
because t1 acquires another lock and t3 acquires another lock.I want no interference between t1
and t3 or t2 and t4.Static synchronization solves this problem.
Inter-thread communication
2.Inter-thread communication
 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:
1. wait()
2. notify()
3. notifyAll()
Note:-
If two or more Threads are communicating with each other, it is called "inter thread"
communication.
Using the synchronized method, two or more threads can communicate indirectly.
wait() method.
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.
Method Description
public final void wait()throws
InterruptedException
waits until object is notified.
public final void wait(long
timeout)throws
InterruptedException
waits for the specified amount of
time.
notify() and notify All() method.
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()
process of inter-thread communication.
Understanding the process of inter-thread communication:-
 The point to point explanation of the above diagram is as follows:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the lock and
exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the object.
Difference between wait and sleep.
wait() sleep()
wait() method releases the lock sleep() method doesn't release the
lock.
is the method of Object class is the method of Thread class
is the non-static method is the static method
is the non-static method is the static method
should be notified by notify() or
notifyAll() methods
after the specified amount of time,
sleep is completed.
Example of inter thread communication in java
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}}
Interrupting a Thread
 Interrupting a Thread:
If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the
interrupt() method on the thread, breaks out the sleeping or waiting state throwing
InterruptedException.
If the thread is not in the sleeping or waiting state, calling the interrupt() method performs
normal behaviour and doesn't interrupt the thread but sets the interrupt flag to true.
There are 3 methods provide in Thread class for thread interruption.
 public void interrupt()
 public static boolean interrupted()
 public boolean isInterrupted()
Thread Exceptions
Note that a call to the sleep() method is always enclosed in try/ catch block.
. it general form will be as follows:
try
{
Thread.sleep(1000);
}
cathc(Exception e)
{ -------
---------
}
Disadvantages of Synchronization
 This way of communications between the threads competing for same resource is called
implicit communication.
 This has one disadvantage due to polling. The polling wastes the CPU time.
 To save the CPU time, it is preferred to go to the inter-thread communication (explicit
communication).

More Related Content

What's hot

What's hot (20)

Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Life cycle-of-a-thread
Life cycle-of-a-threadLife cycle-of-a-thread
Life cycle-of-a-thread
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Java IO
Java IOJava IO
Java IO
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Java thread life cycle
Java thread life cycleJava thread life cycle
Java thread life cycle
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Data types in java
Data types in javaData types in java
Data types in java
 
Java basic
Java basicJava basic
Java basic
 
Java String
Java String Java String
Java String
 
Thread
ThreadThread
Thread
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 

Similar to Multithreading in java

Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languagearnavytstudio2814
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfUnit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfGouthamSoma1
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadKartik Dube
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreadingKuntal Bhowmick
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in javaElizabeth alexander
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptxnimbalkarvikram966
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 

Similar to Multithreading in java (20)

Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming language
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
 
Slide 7 Thread-1.pptx
Slide 7 Thread-1.pptxSlide 7 Thread-1.pptx
Slide 7 Thread-1.pptx
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfUnit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdf
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Internet Programming with Java
Internet Programming with JavaInternet Programming with Java
Internet Programming with Java
 
Java
JavaJava
Java
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in java
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
Threading concepts
Threading conceptsThreading concepts
Threading concepts
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 

More from junnubabu

Priority queue in DSA
Priority queue in DSAPriority queue in DSA
Priority queue in DSAjunnubabu
 
Data struchers and algorithms
Data struchers and algorithmsData struchers and algorithms
Data struchers and algorithmsjunnubabu
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in javajunnubabu
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in pythonjunnubabu
 
Mobile transport layer .
Mobile transport layer .Mobile transport layer .
Mobile transport layer .junnubabu
 
Internet protocol (ip)
Internet protocol (ip)Internet protocol (ip)
Internet protocol (ip)junnubabu
 
Data pre processing
Data pre processingData pre processing
Data pre processingjunnubabu
 
TELECOMMUNICATIONS SYSTEMS
TELECOMMUNICATIONS SYSTEMSTELECOMMUNICATIONS SYSTEMS
TELECOMMUNICATIONS SYSTEMSjunnubabu
 
MEDIUM ACCESS CONTROL
MEDIUM ACCESS CONTROLMEDIUM ACCESS CONTROL
MEDIUM ACCESS CONTROLjunnubabu
 
WIRELESS TRANSMISSION
WIRELESS TRANSMISSIONWIRELESS TRANSMISSION
WIRELESS TRANSMISSIONjunnubabu
 
MOBILE COMMUNICATION
MOBILE COMMUNICATIONMOBILE COMMUNICATION
MOBILE COMMUNICATIONjunnubabu
 
Location based reminder
Location based reminderLocation based reminder
Location based reminderjunnubabu
 

More from junnubabu (12)

Priority queue in DSA
Priority queue in DSAPriority queue in DSA
Priority queue in DSA
 
Data struchers and algorithms
Data struchers and algorithmsData struchers and algorithms
Data struchers and algorithms
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
 
Mobile transport layer .
Mobile transport layer .Mobile transport layer .
Mobile transport layer .
 
Internet protocol (ip)
Internet protocol (ip)Internet protocol (ip)
Internet protocol (ip)
 
Data pre processing
Data pre processingData pre processing
Data pre processing
 
TELECOMMUNICATIONS SYSTEMS
TELECOMMUNICATIONS SYSTEMSTELECOMMUNICATIONS SYSTEMS
TELECOMMUNICATIONS SYSTEMS
 
MEDIUM ACCESS CONTROL
MEDIUM ACCESS CONTROLMEDIUM ACCESS CONTROL
MEDIUM ACCESS CONTROL
 
WIRELESS TRANSMISSION
WIRELESS TRANSMISSIONWIRELESS TRANSMISSION
WIRELESS TRANSMISSION
 
MOBILE COMMUNICATION
MOBILE COMMUNICATIONMOBILE COMMUNICATION
MOBILE COMMUNICATION
 
Location based reminder
Location based reminderLocation based reminder
Location based reminder
 

Recently uploaded

MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGSIVASHANKAR N
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesPrabhanshu Chaturvedi
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 

Recently uploaded (20)

MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 

Multithreading in java

  • 2. Introduction  The program in execution is called "Process".  The program can be structured as set of individual units that can run in parallel. These units can be called as "Threads". Multiprogramming is actually a kind of multitasking.  The multitasking is either process-based or thread base.  Process-based multitasking is nothing but, execution of more than one program concurrently.  Thread-based multitasking allows more than one thread within the program run simultaneously or concurrently.  The process is a Heavy Weight Process. The Thread is a Light Weight Process.
  • 3.  The context-switching of CPU from one process to other requires more overhead as it different address spaces are involved in it.  On the other hand, context-switching is less overhead because of all the threads within the same program.  The objective of all forms of the Multitasking including the multithreading is to utilize the idle time of the processor.  From here onwards, thread-based multitasking is called "Multithreading".
  • 4. Multithreading in Java.  MULTITHREADING in Java is a process of executing two or more threads simultaneously to maximum utilization of CPU. Multithreaded applications execute two or more threads run concurrently. Hence, it is also known as Concurrency in Java. Each thread runs parallel to each other. Mulitple threads don't allocate separate memory area, hence they save memory. Also, context switching between threads takes less time.  Advantages of 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.
  • 5. Multithreading in Java.  Every program that we have been writing has at least one thread, that is, the "main" thread.  Whenever a program starts executing, the JVM is responsible for creating the main thread and calling "main()" method. Along with this main thread, some other threads are also running to carryout the tasks such as "finalization" and "garbage collection". The thread can either die naturally or be forced to die.  Thread dies naturally when it exits from the "run()" method.  Thread can be forced to die by calling "interrupt()" method.
  • 6. 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)  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.
  • 7. Difference between Multiprocessing and Multithreading Process-Based Multitasking Thread-Based Multitasking This deals with "Big Picture" This deals with Details These are Heavyweight tasks These are Lightweight tasks Inter-process communication is expensive and limited Inter-Thread communication is inexpensive. Context switching from one process to another is costly in terms of memory Context switching is low cost in terms of memory, because they run on the same address space This is not under the control of Java This is controlled by Java
  • 8. Life Cycle of a Thread
  • 9.  During the life time of the thread, there are many states it can enter.The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:  Newborn state(New state or start state) The thread is in new state if you create an instance of Thread class but before the invocation of start() method.  At this state we can do the following: 1. Schedule it for running using the start() method. 2. Kill it using stop() method.
  • 10.  Runnable State:  A runnable state means that a thread is ready for execution and waiting for the availability of the processor.  That is the thread has joined the queue of the threads for execution.  If all the threads have equal priority, then they are given time slots for execution in the round rabin fashion, first-come first-serve manner.  The thread that relinquishes the control will join the queue at the end and again waits for its turn. This is known as time slicing.
  • 11.  Running state: Running state means that the processor has given its time to the thread for it execution. The thread runs until it relinquishes the control or it is preempted by the other higher priority thread. As shown in the fig. a running thread can be preempted using the suspend(), or wait(), or sleep() methods.  Blocked state: A thread is said to be in the blocked state when it is prevented from entering into runnable state and subsequently the running state.  Dead state: Every thread has a life cycle. A running thread ends its life when it has completed execution. It is a natural death. However we also can kill the thread by sending the stop() message to it at any time.
  • 12. How to create thread(java.lang.Thread package)  There are two ways to create a thread:  By extending Thread class  By implementing Runnable interface.  Creation of Thread in java is very simple task. There is a class called "Thread", which belongs to the "java.lang.Thread" package.  This package contains one interface also called "Runnable". Both these contain a common method called "run()" which is the heart of the thread.  The run() methods would have the following syntax: Syntax: public void run() { //statement for implementing the thread. }
  • 13. The methods of the Thread class are as follow:  public void run(): is used to perform action for a thread.  public void start(): starts the execution of the thread. JVM 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 void join(): waits for a thread to die.  public void join(long miliseconds): waits for a thread to die for the specified miliseconds.  public int getPriority(): returns the priority of the thread.  public int setPriority(int priority): changes the priority of the thread.  public String getName(): returns the name of the thread.  public void setName(String name): changes the name of the thread.  public Thread currentThread(): returns the reference of currently executing
  • 14.  public int getId(): returns the id of the thread.  public Thread.State getState(): returns the state of the thread.  public boolean isAlive(): tests if the thread is alive.  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 void resume(): is used to resume the suspended thread(depricated).  public void stop(): is used to stop the thread(depricated).  public boolean isDaemon(): tests if the thread is a daemon thread.  public void setDaemon(boolean b): marks the thread as daemon or user thread.  public void interrupt(): interrupts the thread.  public boolean isInterrupted(): tests if the thread has been interrupted.  public static boolean interrupted(): tests if the current thread has been interrupted.  notif()- is calls the thread that is waiting for resource  notifyAll()-is calls the all threads that are waiting for resource
  • 15. Thread Constructors  Thread class:  Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface.  Commonly used Constructors of Thread class:  Thread ()-without arguments, default constructor  Thread(String str)- Thread contains name given as argument  Thread(Thread obj, String str) -takes thread object and string  Thread(class Obj) – takes the runnable class as target object Thread class:
  • 16. The Main Thread  Every java program has a thread called "main" thread.  When the program execution starts, the JVM creates "main" Thread and calls the "main()" method from within that thread.  Along with this JVM also creates other threads for the purpose of the Housekeeping task such as "garbage" collection.  The "main" thread Spawns the other Threads. These spawned threads are called "Child Threads".  The main thread is always is the last thread to finish execution.  We, as Programmer can also take control of the main thread, using the method "currentThread()".  The main thread can be controlled by this method. We can also change the name of the Thread using the method "setName(String name)".
  • 17. Example Program. class MainThread { public static void main(String args[]) { Thread t=Thread.currentThread(); System.out.println("Name of the Thread is:"+t); t.setName(“AIMS ECE 2nd YEAR STUDENTS"); System.out.println("Name of the Thread is:"+t); } }
  • 18. The Thread Priorities  To set a thread’s priority, use the setPriority( ) method, which is a member of Thread.  This is its general form:  final void setPriority(int level)  Here, level specifies the new priority setting for the calling thread. The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10, respectively. To return a thread to default priority, specify NORM_PRIORITY, which is currently 5. These priorities are defined as static final variables within Thread.  You can obtain the current priority setting by calling the getPriority( ) method of Thread, shown here:  final int getPriority( )
  • 19. setPriority() and getpriority() method using.  class PTest { public static void main(String args[]) { //setting the priorities to the thread using the setPriority() method PThread1 pt1=new PThread1(); pt1.setPriority(1); PThread2 pt2=new PThread2(); pt2.setPriority(9); PThread3 pt3=new PThread3(); pt3.setPriority(6); pt1.start(); pt2.start(); pt3.start();  //getting the priority  System.out.println("The pt1 thread priority is :"+pt1.getPriority()); } }
  • 20. Runnable interface in Java  Runnable interface in Java:  The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run . This interface is designed to provide a common protocol for objects that wish to execute code while they are active.  Syntax:  public void run()  Steps involve in the Runnable interface in java: 1. Create a Runnable implementer and implement run() method. 2. Instantiate Thread class and pass the implementer to the Thread , Thread has a constructor which accepts Runnable instance. 3. Invoke start() of Thread instance, start internally calls run() of the implementer.
  • 21. Implementing Runnable Interface package aims; public class aimsRunnableDemo { public static void main(String[] args) { System.out.println("From main() : " + Thread.currentThread().getName()); System.out.println("Creating Runnable Instance..."); Runnable runnable = new Runnable() { @Override public void run() { System.out.println("From run() : " + Thread.currentThread().getName()); } }; System.out.println("Creating a Thread Instance..."); Thread thread = new Thread(runnable); System.out.println("Launching a Thread..."); thread.start(); } }
  • 22. Output:- From main() : main Creating Runnable Instance... Creating a Thread Instance... Launching a Thread... From run() : Thread-0
  • 23. Synchronization in Java.  When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization.  Key to synchronization is the concept of the monitor (also called a semaphore).  A monitor is an object that is used as a mutually exclusive lock, or mutex.  Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor.  All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor.  These other threads are said to be waiting for the monitor.  A thread that owns a monitor can reenter the same monitor if it so desires.
  • 24. Types of Synchronization:  There are two types of synchronization 1. Process Synchronization 2. Thread Synchronization  Process Synchronization On the basis of synchronization, processes are categorized as one of the following two types: 1. Independent Process : Execution of one process does not affects the execution of other processes. 2. Cooperative Process : Execution of one process affects the execution of other processes. Process synchronization problem arises in the case of Cooperative process also because resources are shared in Cooperative processes. Types of Synchronization in Java.
  • 25. Thread Synchronization.  Thread Synchronization There are two types of thread synchronization mutual exclusive and inter-thread communication. 1.Mutual Exclusive Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be done by three ways in java:  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. 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.
  • 26. Synchronized method.  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:- public class SynchronizedCounter{ private int c = 0; public synchronized void increment() { c++; } public synchronized void decrement() { c--; } public synchronized int value() { return c; } }
  • 27. Synchronized block.  Synchronized block. Synchronized block can be used to perform synchronization on any specific resource of the method.  Syntax:- synchronized (object reference expression) { //code block }  Points to remember for Synchronized block Synchronized block is used to lock an object for any shared resource. Scope of synchronized block is smaller than the method.
  • 28. static synchronization.  static synchronization. If you make any static method as synchronized, the lock will be on the class not on object. Problem without static synchronization: Suppose there are two objects of a shared class(e.g. Table)named object1 and object2.In case of synchronized method and synchronized block there cannot be interference betweent1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lock.But there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lock.I want no interference between t1 and t3 or t2 and t4.Static synchronization solves this problem.
  • 29. Inter-thread communication 2.Inter-thread communication  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: 1. wait() 2. notify() 3. notifyAll() Note:- If two or more Threads are communicating with each other, it is called "inter thread" communication. Using the synchronized method, two or more threads can communicate indirectly.
  • 30. wait() method. 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. Method Description public final void wait()throws InterruptedException waits until object is notified. public final void wait(long timeout)throws InterruptedException waits for the specified amount of time.
  • 31. notify() and notify All() method. 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()
  • 32. process of inter-thread communication. Understanding the process of inter-thread communication:-  The point to point explanation of the above diagram is as follows: 1. Threads enter to acquire lock. 2. Lock is acquired by on thread. 3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the lock and exits. 4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state). 5. Now thread is available to acquire lock. 6. After completion of the task, thread releases the lock and exits the monitor state of the object.
  • 33. Difference between wait and sleep. wait() sleep() wait() method releases the lock sleep() method doesn't release the lock. is the method of Object class is the method of Thread class is the non-static method is the static method is the non-static method is the static method should be notified by notify() or notifyAll() methods after the specified amount of time, sleep is completed.
  • 34. Example of inter thread communication in java class Customer{ int amount=10000; synchronized void withdraw(int amount){ System.out.println("going to withdraw..."); if(this.amount<amount){ System.out.println("Less balance; waiting for deposit..."); try{wait();}catch(Exception e){} } this.amount-=amount; System.out.println("withdraw completed..."); } synchronized void deposit(int amount){ System.out.println("going to deposit..."); this.amount+=amount; System.out.println("deposit completed... "); notify(); } } class Test{ public static void main(String args[]){ final Customer c=new Customer(); new Thread(){ public void run(){c.withdraw(15000);} }.start(); new Thread(){ public void run(){c.deposit(10000);} }.start(); }}
  • 35. Interrupting a Thread  Interrupting a Thread: If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behaviour and doesn't interrupt the thread but sets the interrupt flag to true. There are 3 methods provide in Thread class for thread interruption.  public void interrupt()  public static boolean interrupted()  public boolean isInterrupted()
  • 36. Thread Exceptions Note that a call to the sleep() method is always enclosed in try/ catch block. . it general form will be as follows: try { Thread.sleep(1000); } cathc(Exception e) { ------- --------- }
  • 37. Disadvantages of Synchronization  This way of communications between the threads competing for same resource is called implicit communication.  This has one disadvantage due to polling. The polling wastes the CPU time.  To save the CPU time, it is preferred to go to the inter-thread communication (explicit communication).