Multi Threading
Multi Threading
• 1) It doesn't block the user because threads are independent and you can perform multiple
• A thread is a lightweight
subprocess, the 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 uses a shared
memory area.
Multitasking
• Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
utilize the CPU. Multitasking can be achieved in two ways:
• Process-based Multitasking (Multiprocessing)
• Thread-based Multitasking (Multithreading)
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.
Thread-based Multitasking (Multithreading)
• Threads share the same address space.
• A thread is lightweight.
• Cost of communication between the thread is low.
Java Thread class
21) static boolean interrupted() It tests whether the current thread has
been interrupted.
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
• A thread can be in one of the five states. According to sun, there is only 4 states
in thread life cycle in java new, runnable, non-runnable and terminated. There is
no running state.
• But for better understanding the threads, we are explaining it in the 5 states.
• The life cycle of the thread in java is controlled by JVM. The java thread states are
as follows:
1. New
• The thread is in new state if you create an instance of Thread class but before
the invocation of start() method.
2. Runnable
• The thread is in runnable state after invocation of start() method, but the
thread scheduler has not selected it to be the running thread.
3. Running
• The thread is in running state if the thread scheduler has selected it.
4. Non-Runnable (Blocked)
• This is the state when the thread is still alive, but is currently not eligible to
run.
5. Terminated
• A thread is in terminated or dead state when its run() method exits.
How to create thread
•There are two ways to create a thread:
1.By extending Thread class
•Thread class provide constructors and methods to create and perform operations on a thread. Thread class extends Object class and
•Thread()
•Thread(String name)
•Thread(Runnable r)
•Thread(Runnable r,String name)
Commonly used methods of Thread class:
1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
1. public Thread.State getState(): returns the state of the thread.
3. public void yield(): causes the currently executing thread object to temporarily pause and allow other threads
to execute.
11. public static boolean interrupted(): tests if the current thread has been interrupted.
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.
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.
•The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.
• No. After starting a thread, it can never be started again. If you does so,
an eIllegalThreadStateException is thrown. In such case, thread will run once but
for second time, it will throw exception.
• Invoking the run() method from main thread, the run() method goes onto the current call
stack rather than at the beginning of a new call stack.
• 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.
• Naming Thread
• The Thread class provides methods to change and get the name of a thread. By
default, each thread has a name i.e. thread-0, thread-1 and so on. By we can change
the name of the thread by using setName() method. The syntax of setName() and
getName() methods are given below:
• 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.
• There are many java daemon threads running automatically e.g. gc, finalizer etc.
• You can see all the detail by typing the jconsole in the command prompt. The jconsole tool
provides information about the loaded classes, memory usage, running threads etc.
• Points to remember for Daemon Thread in Java
• It provides services to user threads for background supporting tasks. It has no role in life
than to serve user threads.
this thread. That is why JVM terminates the daemon thread if there is no user thread.
• Methods:
No. Method Description
1) public void setDaemon(boolean status) is used to mark the current thread as daemon
thread or user thread.
• In case of thread pool, a group of fixed size threads are created. A thread from the thread
pool is pulled out and assigned a job by the service provider. After completion of the job,
• Java Synchronization is better option where we want to allow only one thread to access the shared
resource
Why use Synchronization?
• The synchronization is mainly used to
1.Process Synchronization
2.Thread Synchronization
1.Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
• 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 Block in Java
• Synchronized block can be used to perform synchronization on any specific resource of the
method.
• Suppose you have 50 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronized block.
• If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
Points to remember for Synchronized block
• Since, both threads are waiting for each other to release the lock, the condition is called
deadlock.
Inter-thread communication in Java
• Inter-thread communication or Co-operation is all about allowing
synchronized threads to communicate with each other.
Method Description
public final void wait()throws waits until object is notified.
InterruptedException
public final void wait(long timeout)throws waits for the specified amount of time.
InterruptedException
• 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()
• notifyAll() method
• Wakes up all threads that are waiting on this object's monitor.
Syntax:
• public final void notifyAll()
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.
• Why wait(), notify() and notifyAll() methods are defined in Object class not
Thread class?
• It is because they are related to lock and object has a lock.
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
should be notified by notify() or notifyAll() after the specified amount of time, sleep is completed.
methods
• 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.
• Let's first see the methods provided by the Thread class for thread interruption.
The 3 methods provided by the Thread class for interrupting a thread