Multithreading in java

This post describes multithreading in java

5/7/20232 min read


Allowing multplie threads to execute simultaneously is called multithreading.These threads gave access to the same menore andcan communicate with each other using the data structures in memory.Both multithreading and multiproccessing can be used for multi tasking but multi threading is more space efficient because it allows threads to share space.

Thread class in java

Thread class is used in java to acheive multithreading.Any class which extends the thread class has to implement run() method,in addition to this thread class contains a start() method.

Different methods of thread class

1)clone() method:-It makes a copy of the thread by copying all the fields in the memory.It also throws clonenotsupported exception.

2)getId():-It is used to obtain an identifier of the thread.

3)getAllStackTrace():-It returns the stack trace of all live threads.

4)isAlive():-It returns true if the thread is alive otherwise false

5)join():-It allows one thread to wait until the other thread completes its execution.

6)setName(String name):-It changes the name of the thread to the value passed in the argument.

7)start():-It is used to start the execution of the thread .The run method of the thread is called upon the execution of this thread.

8)interrupt():- Interrupts the execution of the thread.

9)getPriority():-returns the priority of the thread.

10)yield():-It indicates to the thread scheduler that the current thread is not doing anything particularly important and the processor can be allocarted to another thread if required.

11)sleep(long timeinmillis):-It causes the thread to sleep for specified number of milliseconds.

States of thread.

A thread can be in one of six states at any given point in time. The six states are listed below.

1)New:-When the thread is created for the first time it is in new state.Being in this state means that the thread has not started execution.

2)Runnable:-When the thread is ready to run then it is moved to the runnable state.If the processor is occupied with another thread then at that time the other threads are in runnable state.

3)Blocked:-When the thread is waiting for monitor lock it is blocked.

4)Waiting :-A thread which is waiting for another thread to complete a task remains in the waiting state until the other thread completes the same.

5)Timed Waiting:-A thread which is waiting for another thread to complete a task for a specific amount of time,remains in the timed waiting state.

6)Terminated:-A thread which exited is in terminated state.