Java - Multithreading
Advantages of Java Multithreading
1)It doesn't block the user because threads are independent and you can perform multiple operations at same time.
2) You can perform many operations together so it saves time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU.
Multitasking can be achieved by two ways:
Process-based Multitasking (Multiprocessing)
Thread-based Multitasking (Multithreading)
Threads can be created by using two mechanisms :
Extending the Thread class�
1)We create a class that extends the java.lang.Thread class.
2)This class overrides the run() method available in the Thread class.
3) A thread begins its life inside run() method. We create an object of our new class and call start() method to start the execution of a thread.
4)Start() invokes the run() method on the Thread object.�
Thread creation by implementing the Runnable Interface�
1)We create a new class which implements java.lang.Runnable interface
2) override run() method.
3) Create a thread by defining an object that instantiated from this runnable class as the target of the thread.
4) Then call start() method on this object to run the thread.
Thread Class vs Runnable Interface
Life cycle of a Thread (Thread States)
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(Dead): A thread is in terminated or dead state when its run() method exits.
Methods of Thread class
public void start():starts the execution of the thread.JVM calls the run() method on the thread.
public void stop(): it is used to stop the thread (deprecated).
public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
public void run(): is used to perform action for a thread.
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 wait(): It has been told to wait some event occurs.
public void notify(): A thread which goes into waiting state by calling wait() method will be in waiting state until any other thread calls notify()
public void notifyall(): A thread which goes into waiting state by calling wait() method will be in waiting state until any other thread calls notifyall()
Note:
We can use notify() method to give the notification for only one thread which is waiting for a particular object whereas by the help of notifyAll() methods we can give the notification to all waiting threads of a particular object.
public void setName(): is used to set names to created thread.
public void getName(): is used to get the name of the thread.
public void getState(): is used to get the current state of the thread
.
Thread Priorities
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.
3 constants defined in Thread class
Daemon Thread
Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread automatically.
There are many java daemon threads running automatically e.g. gc, finalizer etc.
Points to remember for Daemon Thread in Java
Methods for Java Daemon thread by Thread class
public void setDaemon(boolean status):
it is used to mark the current thread as daemon thread or user thread.
public boolean isDaemon():
it is used to check that current is daemon.
ThreadGroup in Java
Java provides a convenient way to group multiple threads in a single object. In such way, we can suspend, resume or interrupt group of threads by a single method call.
Constructors of ThreadGroup class
Important methods of ThreadGroup class
int activeCount():returns no. of threads running in current group.
int activeGroupCount():returns a no. of active group in this thread group.
void destroy():destroys this thread group and all its sub groups.
String getName():returns the name of this group.
ThreadGroup getParent():returns the parent of this group.
void interrupt():interrupts all threads of this group.
void list():prints information of this group to standard console.
Synchronization in Java�
Synchronization in java is the capability to 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.
Uses of Synchronization�
The synchronization is mainly used to
Types of Synchronization
There are two types of synchronization
Thread Synchronization�
There are two types of thread synchronization mutual exclusive and inter-thread communication.