Java Multithreading
- ADVANTAGES
- PROCESS BASED MULTITASKING
- THREAD BASED MULTITASKING
- USE OF THREAD
- JAVA THREAD CLASS
- JAVA THREAD METHOD
- THREAD VC RUNNABLE CLASS
- LIFE CYCLE OF THREAD
- JAVA THREAD PRIORITY IN MULTITHREADING
Java's multithreading functionality allows for the simultaneous execution of several threads. The smallest processing unit is a thread, which is a light subprocess. Multiprocessing and multithreading are used to do several tasks at once.
Because threads can benefit from shared memory,
multithreading is favored over multiprocessing. By not creating a specific
region, they preserve memory, and thread context swapping is faster than
process execution. Java multithreading is widely used in games, animations, and
other related tasks.
Advantages of multithreading: -
- The user won't be hampered since threads are autonomous and allow many apps to execute at once.
- It saves time to perform many tasks at once.
- Other threads are independent, therefore this won't affect them in any way. procedures when a single thread encounters an issue.
Multitasking is of two types: -
- Process-based multitasking (Multiprocessing)
- Thread based multitasking (Multithreading)
Process-based multitasking
- Each process has an address in memory. In other words, each process allocates a separate area of memory.
- The process is heavy.
- The cost of transferring data between processes is high.
- Switching from one process to another requires some time to save and load registers, memory cards. . , and lists. , and so on.
Thread-based multitasking (Multithreading)
- Threads share the same address space.
- Threading is lightweight.
- Communication between threads is low.
What is the use of thread in Java?
A thread is a light subprocess that is the smallest
processing unit. We have a separate execution path here.
Threads operate on their own. One thread may
experience an exception without impacting the others. It utilizes a section of
shared memory.
At runtime, several threads can switch contexts.
inside an operating system, there can be several processes and multiple threads
inside a single process.
Java thread class
Java has a class called Thread this Thread class is
used for thread programming. You may create and execute thread activities using
the constructors and methods that the Thread class offers. The Thread class
makes use of the Runnable interface to enhance other classes' capabilities.
Java thread
methods
Thread creation by implementing the runnable
interface
The java. lang package will be implemented by a
newly formed class. creates a runnable interface and substitutes our own run()
method for the run() function. The Thread object is then created, and its
start() function is called.
Let us understand by a program
// the Runnable Interface
Thread
class Vs Runnable class
Java does not enable multiple inheritance;
therefore our expanded Thread class is unable to extend any other classes. Once
we implement the Runnable interface, our class still can extend to other base
classes.
Basic thread functionality can be achieved by
extending the Thread class, as it provides some built-in methods such as
produce(), interrupt(), etc., these methods are not available in the Runnable
interface.
When you use the runnable command, an object that
may be shared by several threads is produced.
The life cycle
of a Thread (Thread states)
A thread lies only in one of the shown states at
any instant:
1. New State
2. Runnable
State
3. Blocked
State
4. Waiting
State
5. Timed
Waiting State
6. Terminated State
Let us understand each one of them separately:
New thread: A new thread when it is created goes
into a new state. When a thread gets to this point, it hasn't started yet. If
and only if a thread's code hasn't begun, it is said to be in a fresh state.
Running state: A thread enters the running state
when it's ready to go. The thread may currently be operating, or it may be
ready to start running at any time. The thread scheduler's role is to determine
when the thread will execute.
In a multithreaded program, time is assigned to
each thread separately. Each thread runs for a certain length of time before
halting and handing the CPU to another thread so that additional threads can
operate. Every thread that is ready for the CPU to run waits patiently for the
CPU to execute an active thread when this happens.
Blocked: Right now, one thread is unable to obtain
the lock, while another thread is managing to accomplish so. A thread changes
from being blocked to being in the running state when it is locked.
Waiting state: A thread has to invoke the wait() or
join() method to go into the waiting state. It goes into the running state when
it gets a notification from another thread or when that thread ends.
Timed Wait: Calling a method with a timeout
parameter causes a thread to be scheduled to wait. We refer to this as a timed
wait. The thread will remain in this state until it times out or gets a
notification. If a thread calls for anything like sleep or a conditional wait,
it's put into a timed wait.
Terminated state: A thread may quit its current
state if any of the following circumstances are met: It conventionally departs
the body. This takes place once the thread's code has finished running.
Because of the appearance of an unforeseen issue,
such as a segment fault or an exception that was ignored.
Implementing
thread states in Java
To find out the current status of a thread while
dealing with Java, use the Thread.getState() method. It includes the java.lang
library. The state variables are defined as an enumeration by the Thread class.
It is summarized below.
1) 1) NEW
It means the thread has not started yet
Ex: public static final Thread.State NEW
2) Runnable
The thread state of the running thread. In executable mode, a thread starts in the Java
virtual machine, but can wait for other operating system resources, such as the CPU.
Ex. public static final Thread.State RUNNABLE
3) Blocked
A thread goes into a blocked state while it waits for the screen lock to be imposed.
A thread cannot leave a blocked state unless it invokes an Object to return to a
synchronized block or function, or it must wait for the screen lock to move to a
synchronized block or Object. wait().
Ex. public static final Thread. State BLOCKED
4) Waiting
Thread state for a waiting thread. A thread is waiting because it calls one of the
following methods: Object. wait with no timeout thread. Join with no
timeout LockSupport.park.
Ex. public static final Thread.State WAITING
5) Timed waiting
The condition of a thread that is waiting for a given amount of time. When a thread
calls one of the following methods with a positive timeout provided, the thread times
out while it waits: Thread.sleepObject.wait with timeout thread. join with
timeoutLockSupport.parkNanosLockSupport.parkUntil.
Ex. public static final Thread.State TIMED_WAITING
6) Terminated
Thread state of the finished thread. The thread is ready.
Ex. public static final Thread.State TERMINATED
Below is
the implementation of the thread:
// Java program to demonstrate thread states
Java thread priority in multithreading
Thread scheduling is the process of allocating a processor to a thread according to its
priority; As we already studied Java is an OOP language that runs in a multi-threaded
environment. In Java, priority is assured at the time of thread creation. Programmers
have the option to manually designate a priority during thread formation, or the JVM
can do it for them automatically.
Each thread in this context has a priority, which is expressed as a number between 1 and 10,
or, to put it more simply, each object has a priority.
The exception is default priority is 5. Minimum priority is 1. Maximum priority is 10.
Here 3 constants are defined in it as follows:\public static int NORM_PRIORITY\public
static int MIN_PRIORITY\ public static int MAX_PRIORITY
To find out how the task is done inside, let's talk about it using an example. Here, we make
the following use of the data gathered above:
We use the current Thread() method to know the name of the current thread. The developer can also use the setName() method if they want to name the threads according to the option for understanding.getName() method is used to get the thread name.
The accepted priority value of a thread is between 1-10.
Let's discuss how we can get and prioritize a thread in Java. public final int getPriority(): The method java. lang.Thread.getPriority() gives the priority of the given thread.public final void set Priority(int newPriority): The method java.lang.Thread.setPriority() sets the preference of the thread to a new thread priority. This method throws an IllegalArgumentException if the value of the new Priority parameter exceeds the min(1) and max(10) limits.
Let us have a program to understand this:
Let us have a program to understand this:
Output Explanation:
The highest priority thread can execute first when
thread execution is prioritized. Assume that the priorities of threads 1, 2,
and 3 are 4, 6, and 1, respectively. As a result, thread t2 is started with a
maximum priority of 6, and then thread t1 and thread t3 come next. The priority
of the main thread always remains 5, however, it can be modified at a later
time. Every other thread's default priority is set by the priority of the main
thread.
What happens if we assign the same priority to every thread, you might wonder. All thread handling is done using the thread scheduler. The example below of what happens when the priorities are the same can be referred to and discussed later as an explanation of the result to better understand conceptually and practically.
No comments:
Post a Comment