Multi-Threading in Java

 

Multi - Threading in Java

Ex : Food Making 


Multitasking

The process of executing one or more tasks concurrently or at the same time is called multitasking. 

The main purpose of multitasking is to use the idle time of CPU.    


Multitasking can be implemented in two ways:

1. Process-based multitasking (Multiprocessing)

2. Thread-based multitasking (Multithreading)


1. Process-based multitasking (Multiprocessing)

- The execution of  multiple programs or processes at the same time (concurrently) this process known as process-based multitasking or program-based multitasking.

- Each program (process) has its own address space in the memory. 

- A process is heavyweight & Cost of communication between the process is high.


2. Thread-based multitasking (Multithreading)

- A program/process uses multiple threads to perform one or more tasks at the same time by a processor is known as thread-based multitasking .

- If we create the multiple Thread of a single process to perform multiple task then it is consider as MultiThreading .






Thread in Java 

Def :

When we write a group of statements in a program, these statements are executed by JVM one by one. This execution process is called thread in Java.

- A thread in Java simply represents a single  path of execution of a group of statements. 

- It is the flow of execution, from beginning to end, of a task.

- Thread in Java is the smallest unit of executable code in a program. 

- It helps to divide a program into multiple parts to speed up the process.





Thread Class & Methods in Java

- Java provides Thread class to achieve thread programming. Thread class provides constructors and methods to create and  perform operations on a thread. Thread class extends Object class and implements Runnable interface.

- The object of thread controls a thread running under JVM.


Methods of Thread Class in Java

1. Static methods  of Thread class :

1. currentThread(): The currentThread() returns the reference of currently executing thread.

2. sleep(): The sleep() method puts currently executing thread to sleep for specified number of milliseconds.

3. yield(): The yield() method pauses the execution of current thread and allows another thread of equal or higher priority that are waiting to execute. 

4. activeCount(): This method returns the number of active threads.


2. Instance methods of Thread class

1. start(): The start() method is used to start the execution of a thread by calling its run() method.

2. run(): The run() method moves the thread into running state.

3. getName(): This method returns the name of the thread. 

4. setName(): This method is used to set the name of a thread. It takes an argument of type String. It returns nothing.

5. getPriority(): This method returns the priority of a thread.  It returns priority value ranging from 1 to 10.The maximum priority is 10, the minimum priority is 1, and normal priority is 5.

6. setPriority(): This method is used to set the priority of a thread.

7. isAlive(): This method is used to check the thread is alive or not.

8. stop(): This method is used to stop the thread.

9. suspend(): The suspend() method is used to suspend or pause a thread.

10.resume(): This method is used to resume the suspended thread.




Creation of Threads in Java 

- Every Java program has at least one thread called main thread.

- Apart from main thread, we can also create our own threads in a program that is called child thread.


There are two ways to create a new thread in Java

1. By extending Thread class (java.lang.Thread)  Ex . MultiThreading1

2. BY implementing Runnable interface (java.lang.Runnable )  Ex . MultiThreading2



Life Cycle of Thread State in Java ( Thread State )

Life Cycle of Thread in Java is basically state transitions of a thread that starts from its birth and ends on its death.


Thread Creation:

  • In Java, you can create a new thread by either extending the Thread class or implementing the Runnable interface. 
  • When using the Thread class, you'll override the run() method with the code you want to execute in the new thread. 
  • If you implement Runnable, you need to provide the implementation for the run() method as well. Once the thread object is created, it's in the "New" state.



State of Thread .

1. New

2. Runnable

3. Running

4. Blocked (Non-runnable state)

5. Dead

  


1. New (Newborn State): 

- After creating the thread object, you call the start() method to begin the execution of the thread. 

-The start() method internally calls the run() method, which contains the actual code that will run in the new thread. Once the start() method is called, the thread moves to the "Runnable" state.


2. Runnable state: 

- Runnable state means a thread is ready for execution. When the start() method is called on a new thread, thread enters into a runnable state.

- In this state, the thread is ready to run, but thread scheduler will decide when it will be executed.


3. Running state:

- Running means Processor (CPU) has allocated time slot to thread for its execution. When thread scheduler selects a thread from the runnable state for execution, it goes into running state

- In this state, the code inside the run() method is executed. The thread will keep running until it either completes its task or is interrupted by other threads or the developer manually stops it.

- A thread can come into running state only from runnable state.


4. Blocked / Waiting  state: 

- A thread is considered to be in the blocked state when it is suspended, sleeping, or waiting for some time in order to satisfy some condition.

- In this state, the thread is not executing its code and is waiting for the event that will unblock it.


5. Dead / Terminated  state: 

- A thread can terminate in two ways: by reaching the end of its run() method or by explicitly calling the stop() method on the thread object.

- Once the thread completes its execution or is manually stopped, it enters the "Dead" state, and it cannot be restarted.

- A thread dies or moves into dead state automatically when its run() method completes the execution of statements. 




    During the life cycle of thread in Java, a thread moves from one state to another state in a variety of ways. This is because in multithreading environment, when multiple threads are executing, only one thread can use CPU at a time. Therefore, a thread is always in any of the five states.


 

Thread Priority in Java

1.Thread priority in Java is a number assigned to a thread that is used by Thread scheduler to decide which thread should be allowed to execute.

2.each thread is assigned a different priority that will decide the order (preference) in which it is scheduled for running.

3.Range of Thread priorities between number of  1 to 10 . 

4.The thread with the highest priority is selected by the scheduler to be executed first.

5.Thread class in Java also provides several priority constants to define the priority of a thread.

1. MIN_PRIORITY = 1

2. NORM_PRIORITY = 5

3. MAX_PRIORTY = 10


Thread Synchronization in Java 

- In Java, multi-threading allows the execution of multiple threads simultaneously, enabling concurrent execution and making efficient use of system resources. 

- when multiple threads access shared resources or data at a time, then issues like data inconsistency, race conditions, and deadlock may arise. To prevent such problems, synchronization is used.

- To avoid that we can use the concept of synchronization where Only one thread can accessed the reasource at a time.

- The purpose (objective) of thread synchronization is to control the use to shared resources. 

- Java provides a keyword named “synchronized” that helps to synchronize thread.

- Only methods or blocks can be synchronized. Variables or classes cannot be synchronized.

- if we use synchronized keyword in our multhithreaded application then that part of code get excecuted by single thread at a time .

- if we want to execute some part of code by single thread at a time than that method should written with synchronized keyword .

- if any method written with synchronized keyword then it is resposibility of JVM to allow only one thread at a time  to execute that method .



Ex :  Road traffic.


syntax : synchronized method 

synchronized void show()

{

  // statements to be synchronized

}


syntax : synchronized block


synchronized(object)

{

  // statements or codes to be synchronized.

}


Synchronizing a block of code is more powerful than synchronized method.


Why use Synchronization?

The synchronization is mainly used to prevent thread interference and consistency problem.


Critical Section 

critical section is consider as a part of code which has executed by single thread at a time.


Deadlock in Java

Deadlock in Java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting for an object lock (lock means use ), that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock.


Ex : Mobile charger using one friend & headphone using friend. then 1st friend need headphone & seconde need charger but they both use it then that condition is deadlock. (lock means use )



conditions for deadlock in a program

Deadlock in a program may occur due to the following conditions. They are as follows:

1. Mutual Exclusion: There is at least one resource that must be held in a non-sharable mode and hence, can be used only by one thread. If another thread requests for it, it should wait until the resource is available.

2. Hold and Wait: This condition occurs when one thread holds a resource and waits for another resource that is held by another thread.

3. No Preemption: The resource will be released only after the execution of thread is completed.

4. Circular Wait: This condition occurs when each thread is waiting for a resource held by the preceding one and the last thread is waiting for a resource held by first thread.


This is called circular wait deadlock. This is because every thread is waiting for a resource held by next one and the last thread is waiting for a resource held by first.







Comments

Popular Posts