Unit 9 Multithreading
Unit 9 Multithreading
In Java, a thread always exists in any one of the following states. These states are:
New: Whenever a new thread is created, it is always in the new state.
Active: When a thread invokes the start() method, it moves from the new state to the active
state. The active state contains two states within it:
one is runnable, and the other is running.
Runnable: A thread, that is ready to run is then moved to the runnable state. In the runnable
state, the thread may be running or may be ready to run at any given instant of time.
Running: When the thread gets the CPU, it moves from the runnable to the running state.
Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently)
then, either the thread is in the blocked state or is in the waiting state.
Terminated: A thread reaches the termination state because of the following reasons:
• When a thread has finished its job, then it exists or terminates normally.
• Abnormal termination: It occurs when some unusual events such as an unhandled
exception or segmentation fault.
Hence, Thread t1 will be processed first, and Thread t4 will be processed last.
Time-slicing scheduling:
Usually, the First Come First Serve algorithm is non-preemptive, which is bad as it may lead
to infinite blocking (also known as starvation). To avoid that, some time-slices are provided to
the threads so that after some time, the running thread has to give up the CPU. Thus, the other
waiting threads also get time to run their job.
In the above diagram, each thread is given a time slice of 2 seconds. Thus, after 2 seconds,
the first thread leaves the CPU, and the CPU is then captured by Thread2. The same process
repeats for the other threads too.
Pre-emptive-Priority Scheduling:
The name of the scheduling algorithm denotes that the algorithm is related to the
priority of the threads. Suppose there are multiple threads available in the runnable state. The
thread scheduler picks that thread that has the highest priority.
Working of the Java Thread Scheduler
Let's understand the working of the Java thread scheduler. Suppose, there are five
threads that have different arrival times and different priorities. Now, it is the responsibility of
the thread scheduler to decide which thread will get the CPU first.
The thread scheduler selects the thread that has the highest priority, and the thread
begins the execution of the job. If a thread is already in runnable state and another thread (that
has higher priority) reaches in the runnable state, then the current thread is pre-empted from
the processor, and the arrived thread with higher priority gets the CPU time.
When two threads (Thread 2 and Thread 3) having the same priorities and arrival time, the
scheduling will be decided on the basis of FCFS algorithm. Thus, the thread that arrives first
gets the opportunity to execute first.
Thread. Sleep() in Java
The Java Thread class provides the two variant of the sleep() method. First one
accepts only an arguments, whereas the other variant accepts two arguments. The method
sleep() is being used to halt the working of a thread for a given amount of time. The time up
to which the thread remains in the sleeping state is known as the sleeping time of the thread.
After the sleeping time is over, the thread starts its execution from where it has left.
Daemon Thread
Daemon thread is a service provider thread that provides services to the user 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
• It provides services to user threads for background supporting tasks. It has no role in life
than to serve user threads.
• Its life depends on user threads.
• It is a low priority thread.
Why JVM terminates the daemon thread if there is no user thread?
The sole purpose of the daemon thread is that it provides services to user thread for
background supporting task. If there is no user thread, why should JVM keep running this
thread. That is why JVM terminates the daemon thread if there is no user thread.
Java Thread Pool
Java Thread pool represents a group of worker threads that are waiting for the job and
reused many times. A thread pool reuses previously created threads to execute current
tasks
In the case of a thread pool, a group of fixed-size threads is created. A thread from the
thread pool is pulled out and assigned a job by the service provider.
Thread Pool Methods.
1. newFixedThreadPool(int s): The method creates a thread pool of the fixed size s.
2. newCachedThreadPool(): The method creates a new thread pool that creates the new
threads when needed but will still use the previously created thread whenever they are
available to use.
3. newSingleThreadExecutor(): The method creates a new thread.
Advantage of Java Thread Pool
1. Better performance: It saves time because there is no need to create a new thread.
2. Real time usage: It is used in Servlet and JSP where the container creates a thread pool
to process the request.
ThreadGroup in Java
Java provides a convenient way to group multiple threads in a single object. In such a
way, we can suspend, resume or interrupt a group of threads by a single method call.
Java thread group is implemented by java.lang.ThreadGroup class. A ThreadGroup
represents a set of threads. A thread group can also include the other thread group. The
thread group creates a tree in which every thread group except the initial thread group has a
parent. A thread is allowed to access information about its own thread group, but it cannot
access the information about its thread group's parent thread group or any other thread
groups.
Constructors of ThreadGroup class
There are only two constructors of ThreadGroup class.
1) By nulling a reference:
i. Employee e=new Employee();
ii. e=null;
3) By anonymous object:
i. new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing. This method is defined in Object
class as:
1. protected void finalize(){}
gc() method: The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.
1. public static void gc(){}