Multithreading in Java

Multithreading in Java : Before we go to Multithreading, we must understand what is Process and Thread.

Process:
Process is nothing but an application running/performing on a device.
For Example: If you are using PC or Laptop then Microsoft Word, Web Browser, Music Player, etc applications are called as Process.
Each process occupies own memory space.
Process are heavy weighted in nature.

Thread:
Threads are nothing but a sub-process. One or more thread makes a process.
For Example: while using MS word, you are typing something on page meanwhile auto spelling is happening, auto case is happening, new page is getting created by default after current page full filled. These all actions are called as Threads.

Advantages of Threads:
Threads occupies only one memory space for all threads.
Threads are light weight in nature.
Intercommunication between threads are less costly whereas intercommunication between processes are more costly.
Every thread in java is an object of java.lang.Thread class.

What is Multithreading? Why do we need of Multithreading?
Running two or more threads at a time is called as ‘Multithreading’ ( Process of executing multiple threads simultaneously ).
Need:
Multithreading results to faster execution of the program because in single threaded environment each task has to be completed before proceeding to next task.
It increases performance of a program.

How do we run a Thread in Java?
We can run a thread by calling start() method or by calling run() method directly as follows (consider t is your thread) :
t.start() and t.run()
If we call the start() method then your thread will get its own thread stack and thread will get run because start() method internally consist of run() method.
If we call the run() method directly then your thread will get run but it will not get its own thread stack. That run() method will act as normal method.

What are the different states of thread in Java?
(Life cycle of a thread)
1st State: Newly created thread (New born state)
2nd State: after calling start() method thread will go into runnable state
3rd State: after calling run() method thread will go into running state
4th State: if you call any interrupted method [ wait() / sleep() ] then thread will go into blocked state
5th State: after calling stop() method thread will get into stopped/dead state

What are different methods used in Multithreading?
There are several methods used in Multithreading for intercommunication between threads and to interrupt the thread execution.

wait() / wait(long ms) / wait(long ms, int ns) :
It is use for intercommunication between threads.
It will pause the execution of thread for several time and it will released an object level lock.


sleep() :
It will forced your thread to sleep for particular amount of period.
It will not release object level lock even after goes to sleep mode.


Yield() :
Yield() method causes to pause current execution of thread to give the chance for waiting thread of same priority.
If there is no waiting thread or all other thread has lower priority then same thread can continue its execution.
If multiple threads are in waiting state with same priority then thread scheduler will decide which thread will get chance for execution.


Join() :
If your thread wants to wait until completion of any other thread execution then we should go for join() method.


Why wait(), notify() and notifyAll() method are in Object class?
The above mentioned methods are used for intercommunication of thread and works on Lock concept.
And the lock concept is applicable for object and class only but not for thread.
Hence we can conclude that wait(), notify() and notifyAll() method must be define in Object class rather than Thread class.

Ways to create Thread in Java

We can create Thread by using two ways in java such as:
1) By extending Thread class
2) By implementing Runnable interface

1) By extending Thread class

2) By implementing Runnable interface:

Which way is better to use?
Defining thread by implementing runnable interface is better to use among two ways (But at the end it is depend on application requirement).
Because if you creating thread by extending thread class then your class cannot extend any other class as java doesn’t support multiple inheritance in terms of classes.

When to use particular way?
If you don’t want to extend your class with any other class rather than Thread class then you should go for by extending Thread class way of creating thread.
But if you want to extend your class with any other class and also want to implement Runnable interface then you should go for by implementing Runnable interface way of creating thread.

What happens if we don’t override run() method?
If we don’t override run() method then default implementation of thread class run() method will get executed.
But Thread class run() method has blank body, hence we will get blank output.

Can we overload run() method of Thread class?
Yes, we can overload run() method of Thread class but Thread class start() method will always call run() method with no argument.
But as we are overloading run() method then its parameter will be different and hence overloaded run() method will not be called by start() method of Thread class, we have to call this overloaded method explicitly.

Priority of Thread in Java

Whenever several thread are in waiting state, thread priority determines which thread to run.
Every thread has a priority.
Priority of thread range lies from 1 to 10.
Priority of main thread is 5.
Thread scheduler uses priority of thread to decide when each thread is allowed to run.
Thread scheduler runs higher priority thread first.
Thread.MIN_PRIORITY=1
Thread.NORM_PRIORITY=5
Thread.MAX_PRIORITY=10

How to change priority of thread?
The setPriority() method is used to set the priority of thread.
Final void setPriority(int value)

How to get priority of thread?
The getPriority() method is used to get the priority of thread.
Final int getPriority()

If two thread have same priority then which thread will get executed first?
We cannot expect about which thread will get executed first, it depends on thread scheduler.
Thread Scheduler can do any of the following thing:

  • It can pick up any thread from pool and run it till it completes.
  • It can give equal opportunity for both thread by time slicing.

What is Daemon Thread? Can we make user define thread as daemon thread if thread is already started?
The thread which executes in background of a program to support other thread is called as ‘Daemon thread’.
Suppose when a thread running at low memory, JVM internally called to garbage collection so that your thread will get enough memory to get executed. So we can say that garbage collector is the best example of Daemon thread.

To Check thread is Daemon not not ( Considering t is thread):
public final boolean isDaemon()
{
t.isDaemon();
//Tests if this thread is a daemon thread
//true if thread is daemon;false otherwise
}


To set thread as Daemon not not ( Considering t is thread):
public final void setDaemon(boolean on)
{
t.setDaemon(true);
//must be invoked before the thread is started.
//on – if true, marks thread as a daemon thread
//on – if false, marks thread as non-daemon thread
}

We cannot make any user define thread as Daemon thread if thread is already started. This has to be done before starting of thread.
We cannot make main thread as Daemon thread because main thread gets started as soon as program gets started.

Synchronization in java

Synchronization is used to overcome the data inconsistency problem in java.
If you make any method or block as synchronized then only one thread can operate on the same object, remaining thread has to wait till first thread gets executed completely.
It means that every thread will operate on same object one by one.
Importance of Synchronization :

  • It is used to overcome data inconsistency problem.
  • It will give regular output instead of irregular output.

Where to use Synchronization?
Where state of an object is going to change.
For example: Bank account balance, ticket reservation system.


Where not to use Synchronization?
Where state of an object is not going to change.
For example: to check Bank account balance, to check seat availability.

To get current object lock:
synchronized(this)
{
//To get current object lock
}

To get particular object lock:
synchronized(b)
{
//To get perticular object lock
}

Without Synchronization:

With Synchronization:

When to have synchronized method and synchronized block?
If you want each and every line of method as synchronized then you must go for synchronized method.
If you want only few line of method as synchronized then you must go for synchronized block.
If you make static method as synchronized then you will get Class level lock
.


Can we synchronized the constructor in Java?
No, a constructor cannot be synchronized in Java.
It will give compile time exception.
Synchronizing a constructor does not make any sense because only the thread that creates an object needs to have access to it while it is being constructed.

Thanks for visiting Ajitation.com, Ajitation is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content.