SlideShare a Scribd company logo
1 of 61
MULTITHREADING
BY LECTURER SURAJ PANDEY CCT COLLEGE
Multithreading in java
Multithreading in java is a process of executing multiple
threads simultaneously.
ď‚—Thread is basically a lightweight sub-process, a smallest unit
of processing. Multiprocessing and multithreading, both are
used to achieve multitasking.
ď‚—But we use multithreading than multiprocessing because
threads share a common 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.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Advantage of Java Multithreading
1) It doesn't block the user because threads are
independent and you can perform multiple operations at
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 exception occur in a single thread.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Multitasking
ď‚—Multitasking is a process of executing multiple tasks
simultaneously. We use multitasking to utilize the CPU.
Multitasking can be achieved by two ways:
1. Process-based Multitasking(Multiprocessing)
2. Thread-based Multitasking(Multithreading)
BY LECTURER SURAJ PANDEY CCT COLLEGE
1) Process-based Multitasking (Multiprocessing)
ď‚—Each process have its own address in memory i.e. each
process allocates separate memory area.
ď‚—Process is heavyweight.
ď‚—Cost of communication between the process is high.
ď‚—Switching from one process to another require some time for
saving and loading registers, memory maps, updating lists
etc.
BY LECTURER SURAJ PANDEY CCT COLLEGE
2) Thread-based Multitasking (Multithreading)
ď‚—Threads share the same address space.
ď‚—Thread is lightweight.
ď‚—Cost of communication between the thread is low.
BY LECTURER SURAJ PANDEY CCT COLLEGE
What is Thread in java
ď‚—A thread is a lightweight sub process, a smallest unit of
processing. It is a separate path of execution.
ď‚—Threads are independent, if there occurs exception in one
thread, it doesn't affect other threads. It shares a common
memory area.
BY LECTURER SURAJ PANDEY CCT COLLEGE
BY LECTURER SURAJ PANDEY CCT COLLEGE
ď‚—As shown in the above figure, thread is executed inside the
process. There is context-switching between the threads.
There can be multiple processes inside the OS and one
process can have multiple threads.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Life cycle of a Thread (Thread States)
ď‚—During the life time of a thread, there are many states it can
enter. They include:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
a thread is always in one of these five states. It can move from
one state to another via a variety of ways as shown in fig.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Newborn
Running Runnable
Blocked
Dead
Start
Stop
Stop
Stop
resume
notify
suspend
sleep wait
Idle
Thread(notR
unnable)
New
Thread
Active
Thread
yield
Killed
Thread
State transition diagram of a thread
BY LECTURER SURAJ PANDEY CCT COLLEGE
ď‚—Newborn state:
ď‚—When we create a thread object, the thread is born and is said to be
in newborn state. The thread is not yet schedule for running. At this
state, we can do only one of the following things with it:
ď‚—Schedule it for running using start() method.
ď‚—Kill it using stop() method
ď‚—If scheduled, it moves to the runnable state . If we attempt to use any other
method at this stage, an exception will be thrown.
BY LECTURER SURAJ PANDEY CCT COLLEGE
ď‚—Runnable State:
ď‚—The runnable state means that the thread is ready for execution and
is waiting for the availability of the processor. That is, the thread
has joined the queue of threads that are waiting for execution. If all
threads have equal priority, then they are given time slots for
execution in round robin fashion, i.e., first-come first-serve
manner. The thread that relinquishes control joins the queue at the
end and again waits for its turn. This process of assigning time to
threads is known as time-slicing.
ď‚—However, if we want a thread to relinquish control, to another
thread to equal priority before its turn comes, we can do so by
using the yield() method
BY LECTURER SURAJ PANDEY CCT COLLEGE
ď‚—Running state:
ď‚—Running means that the processor has given its time to the thread
for its execution. The thread runs until it relinquishes control on its
own or its preempted by a higher priority thread. A running thread
may relinquish its control in one of the following situations.
ď‚—It has been suspended using suspend() method. A suspended thread can be
revived by using the resume() method. This approach is useful when we want
to suspend a thread for some time due to certain reason, but do not want to
kill it.
ď‚—It has been made to sleep, we can put a thread to sleep for a specific time
period using the method sleep(time) where time is milliseconds. This means
that the thread is out of the queue during this time period. The thread re-
enters the runnable state as soon as this time period is elapsed.
BY LECTURER SURAJ PANDEY CCT COLLEGE
ď‚—It has been told to wait until some event occurs. This is done
using the wait() method. The thread can be scheduled to run
again using the notify() method.
BY LECTURER SURAJ PANDEY CCT COLLEGE
ď‚—Blocked state:
ď‚—A thread is said to be blocked when it is prevented from entering
into the runnable state and subsequently the running state. This
happens when the thread is suspended, sleeping, or waiting in order
to satisfy certain requirements. A blocked thread is considered “
not runnable” but not dead and therefore fully qualified to run
again.
BY LECTURER SURAJ PANDEY CCT COLLEGE
ď‚—Dead state:
ď‚—Every thread has a life cycle. A running thread ends its life when it
has completed executing its run() method. It is a natural death.
However, we can kill it by sending the stop message to it at any
state this causing a premature death to it. A thread can be killed as
soon it is born, or while it is running, or even when it is in “not
runnable” (blocked) condition.
BY LECTURER SURAJ PANDEY CCT COLLEGE
How to create thread
ď‚—There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
ď‚—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.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Commonly used methods of Thread class:
 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
thread.
 public int getId(): returns the id of the thread.
 public Thread.State getState(): returns the state of the thread.
BY LECTURER SURAJ PANDEY CCT COLLEGE
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 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.
BY LECTURER SURAJ PANDEY CCT COLLEGE
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().
public void run(): is used to perform action for a thread.
ď‚—Starting a thread:
start() method of Thread class is used to start a newly
created thread. It performs following tasks:
ď‚—A new thread starts(with new callstack).
ď‚—The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run()
method will run.
BY LECTURER SURAJ PANDEY CCT COLLEGE
1)By extending Thread class
class Multi extends Thread{  
public void run(){  
System.out.println("thread is running...");  
}  
public static void main(String args[]){  
Multi t1=new Multi();  
t1.start();  
 }  
}  
BY LECTURER SURAJ PANDEY CCT COLLEGE
2)By implementing the Runnable
interface
class Multi3 implements Runnable{  
public void run(){  
System.out.println("thread is running...");  
}  
public static void main(String args[]){  
Multi3 m1=new Multi3();  
Thread t1 =new Thread(m1);  
t1.start();  
 }  
}  
BY LECTURER SURAJ PANDEY CCT COLLEGE
Thread Scheduler in Java
Thread scheduler in java is the part of the JVM that
decides which thread should run.
ď‚—There is no guarantee that which runnable thread will be
chosen to run by the thread scheduler.
ď‚—Only one thread at a time can run in a single process.
ď‚—The thread scheduler mainly uses preemptive or time slicing
scheduling to schedule the threads.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Sleep method in java
ď‚—The sleep() method of Thread class is used to sleep a thread
for the specified amount of time.
ď‚—Syntax of sleep() method in java
ď‚—The Thread class provides two methods for sleeping a
thread:
ď‚—public static void sleep(long miliseconds)throws
InterruptedException
ď‚—public static void sleep(long miliseconds, int
nanos)throws InterruptedException
BY LECTURER SURAJ PANDEY CCT COLLEGE
Example of sleep method in java
 class TestSleepMethod1 extends Thread{  
 public void run(){  
  for(int i=1;i<5;i++){  
    try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}  
    System.out.println(i);  
  }  
 }  
 public static void main(String args[]){  
  TestSleepMethod1 t1=new TestSleepMethod1();  
  TestSleepMethod1 t2=new TestSleepMethod1();     
t1.start();  
  t2.start();  
 }  
 }  
BY LECTURER SURAJ PANDEY CCT COLLEGE
ď‚—Output:
ď‚— 1
ď‚— 1
ď‚— 2
ď‚— 2
ď‚— 3
ď‚—3
ď‚— 4
ď‚— 4
BY LECTURER SURAJ PANDEY CCT COLLEGE
The join() method:
ď‚—The join() method waits for a thread to die. In other words,
it causes the currently running threads to stop executing
until the thread it joins with completes its task.
ď‚—Syntax:
ď‚—public void join()throws InterruptedException
ď‚—public void join(long milliseconds)throws
InterruptedException
BY LECTURER SURAJ PANDEY CCT COLLEGE
Example of join() method
BY LECTURER SURAJ PANDEY CCT COLLEGE
BY LECTURER SURAJ PANDEY CCT COLLEGE
class TestJoinMethod1 extends Thread{  
 public void run(){  
  for(int i=1;i<=5;i++){  
   try{  
    Thread.sleep(500);  
   }catch(Exception e)
{
System.out.println(e);}  
  System.out.println(i);  
  }  
 }  
public static void main(String args[]){  
 TestJoinMethod1 t1=new TestJoinMethod1();  
 TestJoinMethod1 t2=new TestJoinMethod1();  
 TestJoinMethod1 t3=new TestJoinMethod1();  
 t1.start();  
 try{  
  t1.join();  
 }catch(Exception e){System.out.println(e);}  
  
 t2.start();  
 t3.start();  
 }  
}  
ď‚— Output:1
ď‚— 2
ď‚— 3
ď‚— 4
ď‚— 5
ď‚— 1
ď‚— 1
ď‚— 2
ď‚— 2
ď‚— 3
ď‚— 3
ď‚— 4
ď‚— 4
ď‚— 5
ď‚— 5
  BY LECTURER SURAJ PANDEY CCT COLLEGE
ď‚—As you can see in the above example,when t1 completes its
task then t2 and t3 starts executing.
BY LECTURER SURAJ PANDEY CCT COLLEGE
getName(),setName(String) and getId() method:
BY LECTURER SURAJ PANDEY CCT COLLEGE
 class TestJoinMethod3 extends Thread{  
  public void run(){  
   System.out.println("running...");  
  }  
 public static void main(String args[]){  
  TestJoinMethod3 t1=new TestJoinMethod3();  
  TestJoinMethod3 t2=new TestJoinMethod3();  
  System.out.println("Name of t1:"+t1.getName());  
  System.out.println("Name of t2:"+t2.getName());  
  System.out.println("id of t1:"+t1.getId());    
  t1.start();  
  t2.start();    
  t1.setName(“Ravi");  
  System.out.println("After changing name of t1:"+t1.getName());  
 }  
 }  
BY LECTURER SURAJ PANDEY CCT COLLEGE
ď‚—Output:Name of t1:Thread-0
ď‚— Name of t2:Thread-1
ď‚— id of t1:8
ď‚— running...
ď‚— After changling name of t1:Ravi
ď‚— running...
ď‚—
BY LECTURER SURAJ PANDEY CCT COLLEGE
The currentThread() method:
ď‚—The currentThread() method returns a reference to the
currently executing thread object.
ď‚—Syntax:
ď‚—public static Thread currentThread()
BY LECTURER SURAJ PANDEY CCT COLLEGE
Example of currentThread() method
class TestJoinMethod4 extends Thread
 {  
 public void run(){  
  System.out.println(Thread.currentThread().getName());  
 }  
 }  
 public static void main(String args[]){  
  TestJoinMethod4 t1=new TestJoinMethod4();  
  TestJoinMethod4 t2=new TestJoinMethod4();    
t1.start();  
  t2.start();  
 }  
 }  
BY LECTURER SURAJ PANDEY CCT COLLEGE
ď‚—Output:Thread-0
ď‚— Thread-1
BY LECTURER SURAJ PANDEY CCT COLLEGE
Naming a thread:
ď‚—The Thread class provides methods to change and get the
name of a thread.
public String getName(): is used to return the name of a
thread.
public void setName(String name): is used to change
the name of a thread.
BY LECTURER SURAJ PANDEY CCT COLLEGE
class TestMultiNaming1 extends Thread{  
public void run(){  
   System.out.println("running...");  
  }  
 public static void main(String args[]){  
  TestMultiNaming1 t1=new TestMultiNaming1();  
  TestMultiNaming1 t2=new TestMultiNaming1();  
  System.out.println("Name of t1:"+t1.getName());  
  System.out.println("Name of t2:"+t2.getName());     
t1.start();  
  t2.start();    
 t1.setName("Sonoo Jaiswal");  
  System.out.println("After changing name of t1:"+t1.getName());  
 }  
}  
BY LECTURER SURAJ PANDEY CCT COLLEGE
ď‚—Output:
Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
BY LECTURER SURAJ PANDEY CCT COLLEGE
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
BY LECTURER SURAJ PANDEY CCT COLLEGE
ď‚—3 constants defiend 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.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Example of priority of a Thread:
BY LECTURER SURAJ PANDEY CCT COLLEGE
 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();     
 }  
}     
BY LECTURER SURAJ PANDEY CCT COLLEGE
ď‚—Output:
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
BY LECTURER SURAJ PANDEY CCT COLLEGE
Thread synchronization
ď‚—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 the thread is
achieved is called synchronization.
ď‚—The keyword synchronized helps to solve such problems by
keeping a watch on such locations. For example, the method that
will read information from a file and the method that will update
the same file may be declared as synchronized.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Why use Synchronization
ď‚—The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem
BY LECTURER SURAJ PANDEY CCT COLLEGE
Thread Synchronization
ď‚—There are two types of thread synchronization mutual
exclusive and inter-thread communication.
ď‚—Mutual Exclusive
ď‚—Synchronized method.
ď‚—Synchronized block.
ď‚—static synchronization.
ď‚—Cooperation (Inter-thread communication in java)
BY LECTURER SURAJ PANDEY CCT COLLEGE
ď‚—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
BY LECTURER SURAJ PANDEY CCT COLLEGE
ď‚—synchronized void update()
{
…………….
……………. // code here is synchronized
…………….
}
when we declare a method synchronized, java creates a
“monitor” and hands it over to the thread that calls the method
first time. As long as the thread holds the monitor, no other
thread can enter the synchronized section of code. A monitor is
like a key and the thread that holds the key can only open the
lock.
BY LECTURER SURAJ PANDEY CCT COLLEGE
ď‚—It is also possible to mark a block of code as synchronized as
shown below:
ď‚—synchronized (lock-object)
{
………………..
………………. // code here is synchronized
}
Whenever a thread has completed its work of using synchronized
method (or block of code), it will hand over the monitor to the
next thread that is ready to use the same resource.
BY LECTURER SURAJ PANDEY CCT COLLEGE
ď‚—An interesting situation may occur when two or more threads are
waiting to gain control of a resource. Due to some reasons, the
condition on which the waiting threads rely on to gain control does not
happen. This result in what is known as deadlock. For example, assume
that the thread A must access Method1 before it can release
Method2. because these are mutually exclusive conditions, a deadlock
occurs. The code below illustrate this.
ď‚— Thread A
synchronized method2()
{
synchronized method1()
{
………………..
………………..
}
}
BY LECTURER SURAJ PANDEY CCT COLLEGE
Thread B
synchronized method1()
{
synchronized method2()
{
………………..
………………..
}
}
BY LECTURER SURAJ PANDEY CCT COLLEGE
Deadlock in java
ď‚—Deadlock in java is a part of multithreading. Deadlock can
occur in a situation when a thread is waiting for an object
lock, that is acquired by another thread and second thread is
waiting for an object lock that is acquired by first thread.
Since, both threads are waiting for each other to release the
lock, the condition is called deadlock
BY LECTURER SURAJ PANDEY CCT COLLEGE
BY LECTURER SURAJ PANDEY CCT COLLEGE
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:
1. wait()
2. notify()
3. notifyAll()
BY LECTURER SURAJ PANDEY CCT COLLEGE
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.
BY LECTURER SURAJ PANDEY CCT COLLEGE
Method Description
ď‚—public final void
wait()throws
InterruptedException
ď‚—public final void wait(long
timeout)throws
InterruptedException
ď‚—waits until object is
notified
ď‚—waits for the specified
amount of time
BY LECTURER SURAJ PANDEY CCT COLLEGE
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()
BY LECTURER SURAJ PANDEY CCT COLLEGE
3) notifyAll() method
ď‚—Wakes up all threads that are waiting on this object's
monitor. Syntax:
ď‚—public final void notifyAll()
BY LECTURER SURAJ PANDEY CCT COLLEGE

More Related Content

What's hot

Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrencykshanth2101
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javajunnubabu
 
Java thread life cycle
Java thread life cycleJava thread life cycle
Java thread life cycleArchana Gopinath
 
Threads (operating System)
Threads (operating System)Threads (operating System)
Threads (operating System)Prakhar Maurya
 
Networking in Java
Networking in JavaNetworking in Java
Networking in JavaTushar B Kute
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database ConnectivityInformation Technology
 
Applets in java
Applets in javaApplets in java
Applets in javaWani Zahoor
 
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...Edureka!
 
Thread model in java
Thread model in javaThread model in java
Thread model in javaAmbigaMurugesan
 
Java applet - java
Java applet - javaJava applet - java
Java applet - javaRubaya Mim
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)slire
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streamsHamid Ghorbani
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in JavaM. Raihan
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 

What's hot (20)

Java threading
Java threadingJava threading
Java threading
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java thread life cycle
Java thread life cycleJava thread life cycle
Java thread life cycle
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
Threads (operating System)
Threads (operating System)Threads (operating System)
Threads (operating System)
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Networking in Java
Networking in JavaNetworking in Java
Networking in Java
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
Java applet - java
Java applet - javaJava applet - java
Java applet - java
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 

Similar to Basic of Multithreading in JAva

Slide 7 Thread-1.pptx
Slide 7 Thread-1.pptxSlide 7 Thread-1.pptx
Slide 7 Thread-1.pptxajmalhamidi1380
 
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
 
Threads in Java
Threads in JavaThreads in Java
Threads in JavaHarshaDokula
 
Multi threading
Multi threadingMulti threading
Multi threadinggndu
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptxramyan49
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadKartik Dube
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptxnimbalkarvikram966
 
JAVA THEORY PPT.pptx on based up on the transaction
JAVA THEORY PPT.pptx on based up on the transactionJAVA THEORY PPT.pptx on based up on the transaction
JAVA THEORY PPT.pptx on based up on the transactionSaikiranBiradar3
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfUnit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfGouthamSoma1
 
Java unit 12
Java unit 12Java unit 12
Java unit 12Shipra Swati
 
Multithreadingppt.pptx
Multithreadingppt.pptxMultithreadingppt.pptx
Multithreadingppt.pptxHKShab
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptxTREXSHyNE
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreadingRakesh Madugula
 
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
 

Similar to Basic of Multithreading in JAva (20)

Slide 7 Thread-1.pptx
Slide 7 Thread-1.pptxSlide 7 Thread-1.pptx
Slide 7 Thread-1.pptx
 
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
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Multi threading
Multi threadingMulti threading
Multi threading
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
JAVA THEORY PPT.pptx on based up on the transaction
JAVA THEORY PPT.pptx on based up on the transactionJAVA THEORY PPT.pptx on based up on the transaction
JAVA THEORY PPT.pptx on based up on the transaction
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfUnit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdf
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
 
Multithreadingppt.pptx
Multithreadingppt.pptxMultithreadingppt.pptx
Multithreadingppt.pptx
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Lecture 20
Lecture 20Lecture 20
Lecture 20
 

More from suraj pandey

Systemcare in computer
Systemcare in computer Systemcare in computer
Systemcare in computer suraj pandey
 
vb.net Constructor and destructor
vb.net Constructor and destructorvb.net Constructor and destructor
vb.net Constructor and destructorsuraj pandey
 
Overloading and overriding in vb.net
Overloading and overriding in vb.netOverloading and overriding in vb.net
Overloading and overriding in vb.netsuraj pandey
 
Basic in Computernetwork
Basic in ComputernetworkBasic in Computernetwork
Basic in Computernetworksuraj pandey
 
Computer hardware
Computer hardwareComputer hardware
Computer hardwaresuraj pandey
 
Dos commands new
Dos commands new Dos commands new
Dos commands new suraj pandey
 
History of computer
History of computerHistory of computer
History of computersuraj pandey
 
Dos commands
Dos commandsDos commands
Dos commandssuraj pandey
 
Basic of Internet&email
Basic of Internet&emailBasic of Internet&email
Basic of Internet&emailsuraj pandey
 
Basic fundamental Computer input/output Accessories
Basic fundamental Computer input/output AccessoriesBasic fundamental Computer input/output Accessories
Basic fundamental Computer input/output Accessoriessuraj pandey
 
Introduction of exception in vb.net
Introduction of exception in vb.netIntroduction of exception in vb.net
Introduction of exception in vb.netsuraj pandey
 
Transmission mediums in computer networks
Transmission mediums in computer networksTransmission mediums in computer networks
Transmission mediums in computer networkssuraj pandey
 
Introduction to vb.net
Introduction to vb.netIntroduction to vb.net
Introduction to vb.netsuraj pandey
 
Introduction to computer
Introduction to computerIntroduction to computer
Introduction to computersuraj pandey
 
Computer Fundamental Network topologies
Computer Fundamental Network topologiesComputer Fundamental Network topologies
Computer Fundamental Network topologiessuraj pandey
 
Basic of Computer software
Basic of Computer softwareBasic of Computer software
Basic of Computer softwaresuraj pandey
 
Basic using of Swing in Java
Basic using of Swing in JavaBasic using of Swing in Java
Basic using of Swing in Javasuraj pandey
 
Basic Networking in Java
Basic Networking in JavaBasic Networking in Java
Basic Networking in Javasuraj pandey
 
Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)suraj pandey
 
Graphical User Interface in JAVA
Graphical User Interface in JAVAGraphical User Interface in JAVA
Graphical User Interface in JAVAsuraj pandey
 

More from suraj pandey (20)

Systemcare in computer
Systemcare in computer Systemcare in computer
Systemcare in computer
 
vb.net Constructor and destructor
vb.net Constructor and destructorvb.net Constructor and destructor
vb.net Constructor and destructor
 
Overloading and overriding in vb.net
Overloading and overriding in vb.netOverloading and overriding in vb.net
Overloading and overriding in vb.net
 
Basic in Computernetwork
Basic in ComputernetworkBasic in Computernetwork
Basic in Computernetwork
 
Computer hardware
Computer hardwareComputer hardware
Computer hardware
 
Dos commands new
Dos commands new Dos commands new
Dos commands new
 
History of computer
History of computerHistory of computer
History of computer
 
Dos commands
Dos commandsDos commands
Dos commands
 
Basic of Internet&email
Basic of Internet&emailBasic of Internet&email
Basic of Internet&email
 
Basic fundamental Computer input/output Accessories
Basic fundamental Computer input/output AccessoriesBasic fundamental Computer input/output Accessories
Basic fundamental Computer input/output Accessories
 
Introduction of exception in vb.net
Introduction of exception in vb.netIntroduction of exception in vb.net
Introduction of exception in vb.net
 
Transmission mediums in computer networks
Transmission mediums in computer networksTransmission mediums in computer networks
Transmission mediums in computer networks
 
Introduction to vb.net
Introduction to vb.netIntroduction to vb.net
Introduction to vb.net
 
Introduction to computer
Introduction to computerIntroduction to computer
Introduction to computer
 
Computer Fundamental Network topologies
Computer Fundamental Network topologiesComputer Fundamental Network topologies
Computer Fundamental Network topologies
 
Basic of Computer software
Basic of Computer softwareBasic of Computer software
Basic of Computer software
 
Basic using of Swing in Java
Basic using of Swing in JavaBasic using of Swing in Java
Basic using of Swing in Java
 
Basic Networking in Java
Basic Networking in JavaBasic Networking in Java
Basic Networking in Java
 
Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)
 
Graphical User Interface in JAVA
Graphical User Interface in JAVAGraphical User Interface in JAVA
Graphical User Interface in JAVA
 

Recently uploaded

Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 

Recently uploaded (20)

Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 

Basic of Multithreading in JAva

  • 1. MULTITHREADING BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 2. Multithreading in java ď‚—Multithreading in java is a process of executing multiple threads simultaneously. ď‚—Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. ď‚—But we use multithreading than multiprocessing because threads share a common 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. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 3. Advantage of Java Multithreading 1) It doesn't block the user because threads are independent and you can perform multiple operations at 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 exception occur in a single thread. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 4. Multitasking ď‚—Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved by two ways: 1. Process-based Multitasking(Multiprocessing) 2. Thread-based Multitasking(Multithreading) BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 5. 1) Process-based Multitasking (Multiprocessing) ď‚—Each process have its own address in memory i.e. each process allocates separate memory area. ď‚—Process is heavyweight. ď‚—Cost of communication between the process is high. ď‚—Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 6. 2) Thread-based Multitasking (Multithreading) ď‚—Threads share the same address space. ď‚—Thread is lightweight. ď‚—Cost of communication between the thread is low. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 7. What is Thread in java ď‚—A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution. ď‚—Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It shares a common memory area. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 8. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 9. ď‚—As shown in the above figure, thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the OS and one process can have multiple threads. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 10. Life cycle of a Thread (Thread States) ď‚—During the life time of a thread, there are many states it can enter. They include: 1. Newborn state 2. Runnable state 3. Running state 4. Blocked state 5. Dead state a thread is always in one of these five states. It can move from one state to another via a variety of ways as shown in fig. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 12. ď‚—Newborn state: ď‚—When we create a thread object, the thread is born and is said to be in newborn state. The thread is not yet schedule for running. At this state, we can do only one of the following things with it: ď‚—Schedule it for running using start() method. ď‚—Kill it using stop() method ď‚—If scheduled, it moves to the runnable state . If we attempt to use any other method at this stage, an exception will be thrown. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 13. ď‚—Runnable State: ď‚—The runnable state means that the thread is ready for execution and is waiting for the availability of the processor. That is, the thread has joined the queue of threads that are waiting for execution. If all threads have equal priority, then they are given time slots for execution in round robin fashion, i.e., first-come first-serve manner. The thread that relinquishes control joins the queue at the end and again waits for its turn. This process of assigning time to threads is known as time-slicing. ď‚—However, if we want a thread to relinquish control, to another thread to equal priority before its turn comes, we can do so by using the yield() method BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 14. ď‚—Running state: ď‚—Running means that the processor has given its time to the thread for its execution. The thread runs until it relinquishes control on its own or its preempted by a higher priority thread. A running thread may relinquish its control in one of the following situations. ď‚—It has been suspended using suspend() method. A suspended thread can be revived by using the resume() method. This approach is useful when we want to suspend a thread for some time due to certain reason, but do not want to kill it. ď‚—It has been made to sleep, we can put a thread to sleep for a specific time period using the method sleep(time) where time is milliseconds. This means that the thread is out of the queue during this time period. The thread re- enters the runnable state as soon as this time period is elapsed. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 15. ď‚—It has been told to wait until some event occurs. This is done using the wait() method. The thread can be scheduled to run again using the notify() method. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 16. ď‚—Blocked state: ď‚—A thread is said to be blocked when it is prevented from entering into the runnable state and subsequently the running state. This happens when the thread is suspended, sleeping, or waiting in order to satisfy certain requirements. A blocked thread is considered “ not runnable” but not dead and therefore fully qualified to run again. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 17. ď‚—Dead state: ď‚—Every thread has a life cycle. A running thread ends its life when it has completed executing its run() method. It is a natural death. However, we can kill it by sending the stop message to it at any state this causing a premature death to it. A thread can be killed as soon it is born, or while it is running, or even when it is in “not runnable” (blocked) condition. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 18. How to create thread ď‚—There are two ways to create a thread: 1. By extending Thread class 2. By implementing Runnable interface. ď‚—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. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 19. Commonly used methods of Thread class: ď‚— 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 thread. ď‚— public int getId(): returns the id of the thread. ď‚— public Thread.State getState(): returns the state of the thread. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 20. ď‚—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 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. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 21. 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(). ď‚—public void run(): is used to perform action for a thread. ď‚—Starting a thread: ď‚—start() method of Thread class is used to start a newly created thread. It performs following tasks: ď‚—A new thread starts(with new callstack). ď‚—The thread moves from New state to the Runnable state. When the thread gets a chance to execute, its target run() method will run. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 22. 1)By extending Thread class class Multi extends Thread{   public void run(){   System.out.println("thread is running...");   }   public static void main(String args[]){   Multi t1=new Multi();   t1.start();    }   }   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 23. 2)By implementing the Runnable interface class Multi3 implements Runnable{   public void run(){   System.out.println("thread is running...");   }   public static void main(String args[]){   Multi3 m1=new Multi3();   Thread t1 =new Thread(m1);   t1.start();    }   }   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 24. Thread Scheduler in Java ď‚—Thread scheduler in java is the part of the JVM that decides which thread should run. ď‚—There is no guarantee that which runnable thread will be chosen to run by the thread scheduler. ď‚—Only one thread at a time can run in a single process. ď‚—The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 25. Sleep method in java ď‚—The sleep() method of Thread class is used to sleep a thread for the specified amount of time. ď‚—Syntax of sleep() method in java ď‚—The Thread class provides two methods for sleeping a thread: ď‚—public static void sleep(long miliseconds)throws InterruptedException ď‚—public static void sleep(long miliseconds, int nanos)throws InterruptedException BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 26. Example of sleep method in java ď‚— class TestSleepMethod1 extends Thread{    public void run(){     for(int i=1;i<5;i++){       try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}       System.out.println(i);     }    }    public static void main(String args[]){     TestSleepMethod1 t1=new TestSleepMethod1();     TestSleepMethod1 t2=new TestSleepMethod1();      t1.start();     t2.start();    }   ď‚— }   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 27. ď‚—Output: ď‚— 1 ď‚— 1 ď‚— 2 ď‚— 2 ď‚— 3 ď‚—3 ď‚— 4 ď‚— 4 BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 28. The join() method: ď‚—The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task. ď‚—Syntax: ď‚—public void join()throws InterruptedException ď‚—public void join(long milliseconds)throws InterruptedException BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 29. Example of join() method BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 30. BY LECTURER SURAJ PANDEY CCT COLLEGE class TestJoinMethod1 extends Thread{    public void run(){     for(int i=1;i<=5;i++){      try{       Thread.sleep(500);      }catch(Exception e) { System.out.println(e);}     System.out.println(i);     }    }   public static void main(String args[]){    TestJoinMethod1 t1=new TestJoinMethod1();    TestJoinMethod1 t2=new TestJoinMethod1();    TestJoinMethod1 t3=new TestJoinMethod1();    t1.start();    try{     t1.join();    }catch(Exception e){System.out.println(e);}       t2.start();    t3.start();    }   }  
  • 31. ď‚— Output:1 ď‚— 2 ď‚— 3 ď‚— 4 ď‚— 5 ď‚— 1 ď‚— 1 ď‚— 2 ď‚— 2 ď‚— 3 ď‚— 3 ď‚— 4 ď‚— 4 ď‚— 5 ď‚— 5 ď‚—  BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 32. ď‚—As you can see in the above example,when t1 completes its task then t2 and t3 starts executing. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 33. getName(),setName(String) and getId() method: BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 34. ď‚— class TestJoinMethod3 extends Thread{     public void run(){      System.out.println("running...");     }    public static void main(String args[]){     TestJoinMethod3 t1=new TestJoinMethod3();     TestJoinMethod3 t2=new TestJoinMethod3();     System.out.println("Name of t1:"+t1.getName());     System.out.println("Name of t2:"+t2.getName());     System.out.println("id of t1:"+t1.getId());       t1.start();     t2.start();       t1.setName(“Ravi");     System.out.println("After changing name of t1:"+t1.getName());    }   ď‚— }   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 35. ď‚—Output:Name of t1:Thread-0 ď‚— Name of t2:Thread-1 ď‚— id of t1:8 ď‚— running... ď‚— After changling name of t1:Ravi ď‚— running... ď‚— BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 36. The currentThread() method: ď‚—The currentThread() method returns a reference to the currently executing thread object. ď‚—Syntax: ď‚—public static Thread currentThread() BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 37. Example of currentThread() method class TestJoinMethod4 extends Thread ď‚— {    public void run(){     System.out.println(Thread.currentThread().getName());    }    }    public static void main(String args[]){     TestJoinMethod4 t1=new TestJoinMethod4();     TestJoinMethod4 t2=new TestJoinMethod4();     t1.start();     t2.start();    }   ď‚— }   BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 39. Naming a thread: ď‚—The Thread class provides methods to change and get the name of a thread. ď‚—public String getName(): is used to return the name of a thread. ď‚—public void setName(String name): is used to change the name of a thread. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 41. ď‚—Output: Name of t1:Thread-0 Name of t2:Thread-1 id of t1:8 running... BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 42. 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 BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 43. ď‚—3 constants defiend 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. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 44. Example of priority of a Thread: BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 45. ď‚— 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();       }   }      BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 46. ď‚—Output: running thread name is:Thread-0 running thread priority is:10 running thread name is:Thread-1 running thread priority is:1 BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 47. Thread synchronization ď‚—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 the thread is achieved is called synchronization. ď‚—The keyword synchronized helps to solve such problems by keeping a watch on such locations. For example, the method that will read information from a file and the method that will update the same file may be declared as synchronized. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 48. Why use Synchronization ď‚—The synchronization is mainly used to 1. To prevent thread interference. 2. To prevent consistency problem BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 49. Thread Synchronization ď‚—There are two types of thread synchronization mutual exclusive and inter-thread communication. ď‚—Mutual Exclusive ď‚—Synchronized method. ď‚—Synchronized block. ď‚—static synchronization. ď‚—Cooperation (Inter-thread communication in java) BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 50. ď‚—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 BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 51. ď‚—synchronized void update() { ……………. ……………. // code here is synchronized ……………. } when we declare a method synchronized, java creates a “monitor” and hands it over to the thread that calls the method first time. As long as the thread holds the monitor, no other thread can enter the synchronized section of code. A monitor is like a key and the thread that holds the key can only open the lock. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 52. ď‚—It is also possible to mark a block of code as synchronized as shown below: ď‚—synchronized (lock-object) { ……………….. ………………. // code here is synchronized } Whenever a thread has completed its work of using synchronized method (or block of code), it will hand over the monitor to the next thread that is ready to use the same resource. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 53. ď‚—An interesting situation may occur when two or more threads are waiting to gain control of a resource. Due to some reasons, the condition on which the waiting threads rely on to gain control does not happen. This result in what is known as deadlock. For example, assume that the thread A must access Method1 before it can release Method2. because these are mutually exclusive conditions, a deadlock occurs. The code below illustrate this. ď‚— Thread A synchronized method2() { synchronized method1() { ……………….. ……………….. } } BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 54. Thread B synchronized method1() { synchronized method2() { ……………….. ……………….. } } BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 55. Deadlock in java ď‚—Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 56. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 57. 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: 1. wait() 2. notify() 3. notifyAll() BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 58. 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. BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 59. Method Description ď‚—public final void wait()throws InterruptedException ď‚—public final void wait(long timeout)throws InterruptedException ď‚—waits until object is notified ď‚—waits for the specified amount of time BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 60. 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() BY LECTURER SURAJ PANDEY CCT COLLEGE
  • 61. 3) notifyAll() method ď‚—Wakes up all threads that are waiting on this object's monitor. Syntax: ď‚—public final void notifyAll() BY LECTURER SURAJ PANDEY CCT COLLEGE