Multithreading in Java

Multithreading in Java

What is Multithreading?

Multithreading in java is a process of executing two or more threads simultaneously to maximum utilization of CPU.

Multithreaded applications are where two or more threads run concurrently; hence it is also known as Concurrency in Java. This multitasking is done, when multiple processes share common resources like CPU, memory, etc.

Each thread runs parallel to each other. Threads don't allocate separate memory area; hence it saves memory. Also, context switching between threads takes less time.
Multithreading in java is a process of executing multiple threads simultaneously.

Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation etc.

Advantages of multithread

  • It doesn't block the user because threads are independent and you can perform multiple operations at same time.
  • You can perform many operations together so it saves time.
  • Threads are independent so it doesn't affect other threads if exception occurs in a single thread.
Multitasking

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)

1) Process-based Multitasking (Multiprocessing)
  • Each process has its own address in memory i.e. each process allocates separate memory area.
  • Process is heavyweight.
  • Cost of communication between the processes is high.
  • Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc.
2) Thread-based Multitasking (Multithreading)
  • Threads share the same address space.
  • Thread is lightweight.
  • Cost of communication between the thread is low.

What is Thread in Java?

A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution.
Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It shares a common memory area.



As shown in the above figure, thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the OS and one process can have multiple threads.

Thread Life Cycle in Java

The Life cycle of a thread:

There are various stages of life cycle of thread as shown in above diagram:
1.     New
2.     Runnable
3.     Running
4.     Waiting
5.     Dead



1.     New: In this phase, the thread is created using class "Thread class". It remains in this state till the program starts the thread. It is also known as born thread.
2.     Runnable: In this page, the instance of the thread is invoked with a start method. The thread control is given to scheduler to finish the execution. It depends on the scheduler, whether to run the thread.
3.     Running: When the thread starts executing, then the state is changed to "running" state. The scheduler selects one thread from the thread pool, and it starts executing in the application.
4.     Waiting: This is the state when a thread has to wait. As there multiple threads are running in the application, there is a need for synchronization between threads. Hence, one thread has to wait, till the other thread gets executed. Therefore, this state is referred as waiting state.
5.     Dead: This is the state when the thread is terminated. The thread is in running state and as soon as it completed processing it is in "dead state".



Creating a thread in Java

There are two ways to create a thread in Java:
1)    By extending Thread class.
2)    By implementing Runnable interface.

Methods of Thread class
·         getName(): It is used for Obtaining a thread’s name
·         getPriority(): Obtain a thread’s priority
·         isAlive(): Determine if a thread is still running
·         join(): Wait for a thread to terminate
·         run(): Entry point for the thread
·         sleep(): suspend a thread for a period of time
·         start(): start a thread by calling its run() method

Thread Priorities
·  Thread priorities are the integers which decide how one thread should be treated with respect to the others.
·  Thread priority decides when to switch from one running thread to another, process is called context switching
·    A thread can voluntarily release control and the highest priority thread that is ready to run is given the CPU.
·    A thread can be preempted by a higher priority thread no matter what the lower priority thread is doing. Whenever a higher priority thread wants to run it does.
·   To set the priority of the thread setPriority() method is used which is a method of the class Thread Class.
· In place of defining the priority in integers, we can use MIN_PRIORITY (1)NORM_PRIORITY (5) or MAX_PRIORITY (10).

Methods: isAlive() and join()
·  In all the practical situations main thread should finish last else other threads which have spawned from the main thread will also finish.
·   To know whether the thread has finished we can call isAlive() on the thread which returns true if the thread is not finished.
·   Another way to achieve this by using join() method, this method when called from the parent thread makes parent thread wait till child thread terminates.
·   These methods are defined in the Thread class.
·   We have used isAlive() method in the above examples too.


Java Thread Synchronization

In multithreading, there is the asynchronous behavior of the programs. If one thread is writing some data and another thread which is reading data at the same time, might create inconsistency in the application.
When there is a need to access the shared resources by two or more threads, then synchronization approach is utilized.
Java has provided synchronized methods to implement synchronized behavior.
In this approach, once the thread reaches inside the synchronized block, then no other thread can call that method on the same object. All threads have to wait till that thread finishes the synchronized block and comes out of that.
In this way, the synchronization helps in a multithreaded application. One thread has to wait till other thread finishes its execution only then the other threads is allowed for execution.
It can be written in the following form:

synchronized (object)
        //Block of statements to be synchronized
}




Comments

Popular posts from this blog

પટેલ સમાજનો ઈતિહાસ જાણો : કોણ અને ક્યાંથી આવ્યા હતા પાટીદારો

Python HTML Generator using Yattag Part 1

Java Event Delegation Model, Listener and Adapter Classes