M8-Threads - 2.0
M8-Threads - 2.0
Thread:-
1) Thread is nothing but a separate path of sequential execution.
2) The independent execution technical name is called thread.
3) Whenever different parts of the program are executed simultaneously,
each and every part is called thread.
4) The thread is a light weight process because whenever we are creating
a thread it is not occupying the separate memory it uses the same memory.
Whenever the memory is shared means it is not consuming more memory.
5) Executing more than one thread a time is called multithreading.
Information about main Thread
When a Java program starts one Thread is running immediately. That
thread is called the main thread of your program.
1. It is used to create a new Thread(child Thread).
2. It must be the last thread to finish the execution because it performs
various actions.
It is possible to get the current thread reference by using currentThread()
method; it is a static public method present in Thread class.
The main important application areas of the multithreading are
1. Developing video games
2. Implementing multimedia graphics.
3. Developing animations
=========================================
A thread can be created in two ways:-
1) By extending Thread class.
2) By implementing java.lang.Runnable interface.
Thread Scheduler:
· If multiple Threads are waiting to execute then which Thread will execute
1st is decided by “Thread Scheduler” which is part of JVM.
· Which algorithm or behavior followed by Thread Scheduler we can’t
expect exactly is the JVM vendor dependent hence in multithreading.
2)Ready :- t.start()
5)Dead State:-If the business logic of the project is completed means run()
over thread goes dead state.
❖ After starting a Thread we are not allowed to restart the same Thread
once again otherwise we will get a runtime exception saying
“IllegalThreadStateException”.
Naming Thread
The Thread class provides methods to change and get the name of a
thread. By default, each thread has a name i.e. thread-0, thread-1 and so
on …
We can change the name of the thread by using setName() method. The
syntax of setName() and getName() methods are given below
1. public String getName(): is used to return the name of a thread.
2. public void setName(String name): is used to change the name of a
thread.
yield()
❖ Suppose there are three threads t1, t2, and t3. Thread t1 gets the
processor and starts its execution .
❖ Thread t2 and t3 are in Ready/Runnable state.
❖ Completion time for thread t1 is 5 hour and completion time for t2 is 5
minutes. Since t1 will complete its execution after 5 hours, t2 has to wait
for 5 hours to just finish the 5 minutes job.
❖ In such scenarios where one thread is taking too much time to complete its
execution, we need a way to prevent execution of a thread in between if
something important is pending.
❖ yeild() helps us in doing so.
❖ yield() basically means that the thread is not doing anything particularly
important and if any other threads or processes need to be run, they
should run. Otherwise, the current thread will continue to run.
Use of yield method:
● Whenever a thread calls java.lang.Thread.yield method, it gives a hint
to the thread scheduler that it is ready to pause its execution. Thread
scheduler is free to ignore this hint.
● If any thread executes the yield method , the thread scheduler checks if
there is any thread with same or higher priority than this thread. If the
processor finds any thread with higher or same priority then it will move
the current thread to Ready/Runnable state and give the processor to
another thread and if not – current thread will keep executing.
Example code
Note:
● Once a thread has executed the yield method and there are many
threads with the same priority waiting for the processor, then we can't
specify which thread will get an execution chance first.
● The thread which executes the yield method will enter in the Runnable
state from Running state.
● Once a thread pauses its execution, we can't specify when it will get a
chance again; it depends on the thread scheduler.
● Underlying platform must provide support for preemptive scheduling if
we are using yield methods
sleep(): This method causes the currently executing thread to sleep for the
specified number of milliseconds, subject to the precision and accuracy of
system timers and schedulers..
// sleep for the specified number of milliseconds
public static void sleep(long millis) throws
InterruptedException
Note:
● Based on the requirement we can make a thread to be in sleeping state
for a specified period of time
● Sleep() causes the thread to definitely stop executing for a given
amount of time; if no other thread or process needs to be run, the CPU
will be idle (and probably enter a power saving mode).
Join() : The join() method of a Thread instance is used to join the start of a
thread’s execution to the end of another thread’s execution such that a
thread does not start running until another thread ends. If join() is called on a
Thread instance, the currently running thread will block until the Thread instance
has finished executing.
==========================
Synchronization
● Synchronized is the keyword applicable for methods and blocks but not for
classes and variables.
● · If a method or block is declared as synchronized then at a time only one Thread
is allowed to execute that method or block on the given object.
● · The main advantage of synchronized keywords is we can resolve data
inconsistency problems.
● · But the main disadvantage of synchronized keyword is it increases waiting time
of the Thread and affects performance of the system.
● · Hence if there is no specific requirement then never recommend to use
synchronized keywords.
● · Internally synchronization concept is implemented by using lock concept.
● · Every object in java has a unique lock. Whenever we are using synchronized
keywords then only the lock concept will come into the picture.
● ·If a Thread wants to execute any synchronized method on the given object , 1st
it has to get the lock of that object.
● Once a Thread gets the lock of that object then it’s allowed to execute any
synchronized method on that object. If the synchronized method execution
completes then automatically Thread releases lock.
● While a Thread executing any synchronized method the remaining Threads are
not allowed to execute any synchronized method on that object simultaneously.
But remaining Threads are allowed to execute any non-synchronized method
simultaneously. [lock concept is implemented based on object but not based on
method]
Example code :
package sync;
M1 m1 = new M1();
m1.s1 = s;
M2 m2 = new M2();
m2.s1 = s;
m1.start();
m2.start();
}
SourceTable s1;
@Override
public void run() {
s1.tablePrint(5);
SourceTable s1;
@Override
public void run() {
s1.tablePrint(10);
Source table:
package sync;
For Synchronization.
M1 m1 = new M1();
m1.s1 = source1;
M2 m2 = new M2();
m2.s1 = source1;
m1.start();
m2.start();
Now both the threads are working on different objects.
I.e : remaining threads can execute normal static methods, normal instance
methods.
Notify vs NotifyAll.
notify() and notifyAll() methods with wait() method are used for communication
between the threads. A thread which goes into a waiting state by calling wait()
method will be in waiting state until any other thread calls either notify() or
notifyAll() method on the same object.
Notifying a thread by JVM : If multiple threads are waiting for the notification
and we use notify() method then only one thread gets the notification and
the remaining thread has to wait for further notification. Which thread will get the
notification we can’t expect because it totally depends upon the JVM. But when
we use notifyAll() method then multiple threads get the notification but execution
of threads will be performed one by one because thread requires lock and only
one lock is available for one object.