MultithreadingMultithreading
By
Nilesh Dalvi
Lecturer, Patkar-Varde College.Lecturer, Patkar-Varde College.
http://www.slideshare.net/nileshdalvi01
Java and Data StructuresJava and Data Structures
Introduction
• Multithreading in java is a process of executing
multiple threads simultaneously.
• Thread is basically a lightweight sub-process, a
smallest unit of processing.
• Java Multithreading is mostly used in games,
animation etc.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Thread
• A thread is a light-weight 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.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
t1
t2
t3
Process1
Process2
Process3
Life Cycle of Thread
• A thread can be in one of the five states.
• Life cycle of the thread in java is controlled by JVM.
• The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Life Cycle of Thread
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
NewNew
RunnableRunnable
RunningRunning
TerminatedTerminated
Non-
Runnable
(Blocked)
Non-
Runnable
(Blocked)
start()
run()
Method exits
stop()
run()
Sleep done,
resume, notify
Sleep,
suspend, wait
Life Cycle of Thread
1. New state:
– The thread is in new state if you create an instance of
Thread class but before the invocation of start() method.
– It is also referred to as newborn state.
1. Runnable state:
– The thread is in runnable state after invocation of start()
method, but the thread scheduler has not selected it to be
the running thread.
– Thread scheduler: Part of JVM that decides which thread
should run.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Life Cycle of Thread
3. Running state:
– thread is in running state if the thread scheduler has
selected it.
– It has been suspended using suspend() method and
retrieved using resume() method.
– It has been made to sleep using sleep() method for specified
time.
– It has been told to wait until some event occurs, using wait()
method, rescheduled using notify() method.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Life Cycle of Thread
4. Non-Runnable(Blocked) state:
– This is the state when the thread is still alive, but is currently
not eligible to run.
5. Terminated (Dead)state:
– A thread is in terminated or dead state when its run()
method exits.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Creating thread
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
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:
– Thread()
– Thread(String name)
– Thread(Runnable r)
– Thread(Runnable r, String name)
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Thread Class
Commonly used Method:
•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
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.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Thread Class
Commonly used Method:
•public int getId(): returns the id 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.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Extending Thread Class
• It includes following steps:
– Declare the class as extending Thread class.
– Implement the run() method that is responsible for
executing the sequence of code that the thread will execute.
– Create a thread object and call the start() method to initiate
the thread execution.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Extending Thread Class
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
class MyThread extends Thread
{
public void run ()
{
System.out.println("Thread Started...!");
for (int count = 1, row = 1; row < 10; row++, count++)
{
for (int i = 0; i < count; i++)
System.out.print ('*');
System.out.print ('n');
}
}
}
class ThreadDemo
{
public static void main (String [] args)
{
MyThread mt = new MyThread ();
mt.start ();
}
}
Implementing Runnable interface
• It includes following steps:
– Declare the class as implementing the runnable interface.
– Implement the run() method.
– Create a thread by defining an object that is instantiated
from this runnable class as the target of the thread.
– Call the threads start() method to run the thread.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Implementing Runnable interface
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
class MyThread implements Runnable
{
public void run ()
{
System.out.println("Thread Started...!");
for (int count = 1, row = 1; row < 10; row++, count++)
{
for (int i = 0; i < count; i++)
System.out.print ('*');
System.out.print ('n');
}
}
}
class ThreadDemo
{
public static void main (String [] args)
{
MyThread mt = new MyThread ();
Thread t = new Thread (mt);
t.start ();
}
}
Sleep()
• sleep() method of Thread class is used to sleep a thread for the
specified milliseconds of time.
• Syntax:
public static void sleep(long miliseconds) throws InterruptedException
public static void sleep(long miliseconds, int nanos) throws InterruptedException
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
join()
• 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
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Naming a thread:
• The Thread class provides methods to change and get the name
of a thread.
• public String getName():
– It is used to return the name of a thread.
• public void setName(String name):
– It is used to change the name of a thread.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
currentThread()
• currentThread() method returns a reference to the currently
executing thread object.
• Syntax:
public static Thread currentThread():
– returns the reference of currently running thread.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Priority of a Thread (Thread Priority):
• Each thread have a priority.
• Priorities are represented by a number between 1 and 10.
• In most cases, thread scheduler schedules the threads
according to their priority (known as preemptive scheduling).
• But it is not guaranteed because it depends on JVM
specification that which scheduling it chooses.
• 3 constants defined in Thread class:
– public static int MIN_PRIORITY
– public static int NORM_PRIORITY
– public static int MAX_PRIORITY
• Default priority of a thread is 5 (NORM_PRIORITY).
• MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Performing multiple task by multiple thread
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Synchronization
• Synchronization in java is the capability of control the access of
multiple threads to any shared resource.
• Java Synchronization is better option where we want to allow
only one thread to access the shared resource.
• synchronized method:
– If you declare any method as synchronized, it is known as synchronized
method.
– Synchronized method is used to lock an object for any shared resource.
– When a thread invokes a synchronized method, it automatically acquires
the lock for that object and releases it when the thread completes its
task.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Q & A

7. Multithreading

  • 1.
    MultithreadingMultithreading By Nilesh Dalvi Lecturer, Patkar-VardeCollege.Lecturer, Patkar-Varde College. http://www.slideshare.net/nileshdalvi01 Java and Data StructuresJava and Data Structures
  • 2.
    Introduction • Multithreading injava is a process of executing multiple threads simultaneously. • Thread is basically a lightweight sub-process, a smallest unit of processing. • Java Multithreading is mostly used in games, animation etc. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 3.
    Thread • A threadis a light-weight 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. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). t1 t2 t3 Process1 Process2 Process3
  • 4.
    Life Cycle ofThread • A thread can be in one of the five states. • Life cycle of the thread in java is controlled by JVM. • The java thread states are as follows: 1. New 2. Runnable 3. Running 4. Non-Runnable (Blocked) 5. Terminated Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 5.
    Life Cycle ofThread Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). NewNew RunnableRunnable RunningRunning TerminatedTerminated Non- Runnable (Blocked) Non- Runnable (Blocked) start() run() Method exits stop() run() Sleep done, resume, notify Sleep, suspend, wait
  • 6.
    Life Cycle ofThread 1. New state: – The thread is in new state if you create an instance of Thread class but before the invocation of start() method. – It is also referred to as newborn state. 1. Runnable state: – The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread. – Thread scheduler: Part of JVM that decides which thread should run. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 7.
    Life Cycle ofThread 3. Running state: – thread is in running state if the thread scheduler has selected it. – It has been suspended using suspend() method and retrieved using resume() method. – It has been made to sleep using sleep() method for specified time. – It has been told to wait until some event occurs, using wait() method, rescheduled using notify() method. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 8.
    Life Cycle ofThread 4. Non-Runnable(Blocked) state: – This is the state when the thread is still alive, but is currently not eligible to run. 5. Terminated (Dead)state: – A thread is in terminated or dead state when its run() method exits. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 9.
    Creating thread There aretwo ways to create a thread: 1. By extending Thread class 2. By implementing Runnable interface. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 10.
    Thread Class • Threadclass provide constructors and methods to create and perform operations on a thread. • Thread class extends Object class and implements Runnable interface. • Commonly used constructors: – Thread() – Thread(String name) – Thread(Runnable r) – Thread(Runnable r, String name) Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 11.
    Thread Class Commonly usedMethod: •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 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. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 12.
    Thread Class Commonly usedMethod: •public int getId(): returns the id 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. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 13.
    Extending Thread Class •It includes following steps: – Declare the class as extending Thread class. – Implement the run() method that is responsible for executing the sequence of code that the thread will execute. – Create a thread object and call the start() method to initiate the thread execution. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 14.
    Extending Thread Class NileshDalvi, Lecturer@Patkar-Varde College, Goregaon(W). class MyThread extends Thread { public void run () { System.out.println("Thread Started...!"); for (int count = 1, row = 1; row < 10; row++, count++) { for (int i = 0; i < count; i++) System.out.print ('*'); System.out.print ('n'); } } } class ThreadDemo { public static void main (String [] args) { MyThread mt = new MyThread (); mt.start (); } }
  • 15.
    Implementing Runnable interface •It includes following steps: – Declare the class as implementing the runnable interface. – Implement the run() method. – Create a thread by defining an object that is instantiated from this runnable class as the target of the thread. – Call the threads start() method to run the thread. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 16.
    Implementing Runnable interface NileshDalvi, Lecturer@Patkar-Varde College, Goregaon(W). class MyThread implements Runnable { public void run () { System.out.println("Thread Started...!"); for (int count = 1, row = 1; row < 10; row++, count++) { for (int i = 0; i < count; i++) System.out.print ('*'); System.out.print ('n'); } } } class ThreadDemo { public static void main (String [] args) { MyThread mt = new MyThread (); Thread t = new Thread (mt); t.start (); } }
  • 17.
    Sleep() • sleep() methodof Thread class is used to sleep a thread for the specified milliseconds of time. • Syntax: public static void sleep(long miliseconds) throws InterruptedException public static void sleep(long miliseconds, int nanos) throws InterruptedException Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 18.
    join() • join() methodwaits 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 Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 19.
    Naming a thread: •The Thread class provides methods to change and get the name of a thread. • public String getName(): – It is used to return the name of a thread. • public void setName(String name): – It is used to change the name of a thread. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 20.
    currentThread() • currentThread() methodreturns a reference to the currently executing thread object. • Syntax: public static Thread currentThread(): – returns the reference of currently running thread. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 21.
    Priority of aThread (Thread Priority): • Each thread have a priority. • Priorities are represented by a number between 1 and 10. • In most cases, thread scheduler schedules the threads according to their priority (known as preemptive scheduling). • But it is not guaranteed because it depends on JVM specification that which scheduling it chooses. • 3 constants defined in Thread class: – public static int MIN_PRIORITY – public static int NORM_PRIORITY – public static int MAX_PRIORITY • Default priority of a thread is 5 (NORM_PRIORITY). • MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 22.
    Performing multiple taskby multiple thread Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 23.
    Synchronization • Synchronization injava is the capability of control the access of multiple threads to any shared resource. • Java Synchronization is better option where we want to allow only one thread to access the shared resource. • synchronized method: – If you declare any method as synchronized, it is known as synchronized method. – Synchronized method is used to lock an object for any shared resource. – When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 24.