Multithreading
•A thread is a light-weight smallest part of a process that can run
concurrently with the other parts(other threads) of the same
process.
• Threads are independent because they all have separate path of
execution that’s the reason if an exception occurs in one thread,
it doesn’t affect the execution of other threads.
•All threads of a process share the common memory. The process of
executing multiple threads simultaneously is known as
multithreading.
Multithreading
•The main purpose of multithreading is to provide simultaneous
execution of two or more parts of a program to maximum utilize
the CPU time. A multithreaded program contains two or more
parts that can run concurrently. Each such part of a program called
thread.
Thread Life Cycle
•A thread can be in one of the following states:
NEW – A thread that has not yet started is in this state.
RUNNABLE – A thread executing in the Java virtual machine is
in this state.
BLOCKED – A thread that is blocked waiting for a monitor lock is
in this state.
WAITING – A thread that is waiting indefinitely for another thread
to perform a particular action is in this state.
TIMED_WAITING – A thread that is waiting for another thread
to perform an action for up to a specified waiting time is in this
state. TERMINATED – A thread that has exited is in this state.
Creating a thread in Java
•There are two ways to create a thread in Java:
1)By extending Thread class. Thread class has following methods and
many more.
•2) By implementing Runnable
interface.
Thread creation by extending Thread
class
Thread creation by implementing
Runnable Interface