Multi Threading
Multi Threading
Programming
What is Multitasking?
process. CPU switches from one program to another so quickly to complete all the
More than one part of program called threads is executed simultaneously. Multithreading
is also timesharing process. CPU switches from one activity to another activity within the
weight process because the activities/threads share the same memory location.
Difference between multitasking and multithreading:
A thread can be in one of the five states. A thread goes through various stages in its life
cycle. For example, a thread is born, started, runs, and then dies.
The 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
Thread Life Cycle
Thread Life Cycle
NEW – a newly created thread that has not yet started the execution
RUNNABLE – either running or ready for execution but it's waiting for resource allocation
block/method
WAITING – waiting for some other thread to perform a particular action without any time
limit
TIMED_WAITING – waiting for some other thread to perform a specific action for a
specified period
New
A NEW Thread (or a Born Thread) is a thread that's been created but not yet started. It
remains in this state until we start it using the start() method.
The following code snippet shows a newly created thread that's in the NEW state:
Runnable
When we've created a new thread and called the start() method on that, it's moved
from NEW to RUNNABLE state. Threads in this state are either running or ready to run,
but they're waiting for resource allocation from the system.
In a multi-threaded environment, the Thread-Scheduler (which is part of JVM) allocates a
fixed amount of time to each thread. So it runs for a particular amount of time, then
relinquishes the control to other RUNNABLE threads.
Thread Life Cycle
Output:
Runnable
Thread Life Cycle
Blocked
A thread is in the BLOCKED state when it's currently not eligible to run. It enters this state
when it is waiting for a monitor lock and is trying to access a section of code that is
locked by some other thread.
Output:
Blocked
Thread Life Cycle
In this code:
Waiting
A thread is in WAITING state when it's waiting for some other thread to perform a
particular action. According to JavaDocs, any thread can enter this state by calling any
one of the following three methods:
object.wait()
thread.join() or
LockSupport.park()
Note that in wait() and join() – we do not define any timeout period as that scenario is
covered in the next section.
Creating Threads
How to create thread
There are two ways to create a thread:
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()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
Creating Threads
1) Java Thread Example by extending Thread class
class Create_Thread extends Thread
{
public void run()
{
System.out.println("concurrent thread started running..");
}
}
class Demo
{
public static void main(String args[])
{
Create_Thread mt = new Create_Thread();
mt.start();
}
}
Output:
concurrent thread started running..
Creating Threads
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.
Creating Threads
class MyThread implements Runnable
{
public void run()
{
System.out.println("concurrent thread started running..");
}
}
class MyThreadDemo
{
public static void main(String args[])
{
MyThread mt = new MyThread();
Thread t = new Thread(mt);
t.start();
}
}
Output:
concurrent thread started running..
Thread Methods
Commonly used methods of Thread class:
Used in server applications for improving high throughput and resource utilization.
Parallelize tasks.
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 schedular schedules the threads according to their priority .
When we start two or more threads within a program, there may be a situation when
multiple threads try to access the same resource and finally they can produce unforeseen
result due to concurrency issues. For example, if multiple threads try to write within a
same file then they may corrupt the data because one of the threads can override data or
while one thread is opening the same file at the same time another thread might be
closing the same file.
So there is a need to synchronize the action of multiple threads and make sure that only
one thread can access the resource at a given point in time. This is implemented using a
concept called monitors. Each object in Java is associated with a monitor, which a thread
can lock or unlock. Only one thread at a time may hold a lock on a monitor.
Java programming language provides a very handy way of creating threads and
synchronizing their task by using synchronized blocks. You keep shared resources within
this block. Following is the general form of the synchronized statement −
Synchronizing Threads
synchronized(objectidentifier) {
// Access shared variables and other shared
resources
}
Inter-thread Communication
If you are aware of interprocess communication then it will be easy for you to understand
interthread communication. Interthread communication is important when you develop
an application where two or more threads exchange some information. 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()
Inter-thread Communication
When we apply wait() method on current running thread release the monitor and go
to sleep until another thread doesn’t call notify() with same object monitor.
What is thread?
Difference between multitasking and multithreading.
Thread lifecycle
Thread methods
Ways to create thread in java
Synchronized threads
Inter-thread communication.