Multithreading
_______________________________
_______________________________
Executing several tasks simultaneously known as multitasking. There are two types of multitasking
Whether it is a process based or thread based, the main objective of multitasking is to improve performance of the system by reduce the response time. the main application areas of multitasking are developing video games, multimedia graphics, implementing animations etc.
Java provides inbuilt support for multi-threading by introducing a rich API (Thread, Runnable ThreadGroup, ThreadLocal)
We can define a thread in the following two ways.
Thread Scheduler - when multiple threads are waiting to get chance for execution, this decides by thread scheduler. whose behavior is JVM vendor dependent, so we can't expect exact execution order and exact output. Thread scheduler is part of JVM.
To start a thread, the required mandatory activities like registering thread with thread scheduler will be perform automatically by thread class start( ) method. because programmer is not responsible to perform this activity the programmer only defines the job of the thread. hence, thread class start( ) plays very important role and without executing that method there is no chance of starting a new thread.
t.start( )
2. Ready / Runnable State
If thread scheduler allocates CPU
3. Running State
yield( ) join( ) sleep( ) wait( ) notify( ) notify All( )
4. If run( ) method completed
Dead State
We can define a thread by implementing Runnable Interface also. Runnable Interface present in java.lang package and contains only one method run()
Every thread in Java has some name, it may be provided by programmer or default name by the JVM. We have two methods of thread class to get and set name of thread.
public final String getName( );
public final void setName(StringName);
class Test {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName()); // main
Thread.currentThread( ).setName("arjava");
System.out.println(Thread.currentThread( ).getName()); // arjava
} }
Note: We can get current executing thread reference by using the following method of thread class. public class Thread current.Thread( );
Every thread in Java has some priority but the range of thread priorities is 1 to 10, 1 is least and 10 is highest. Thread class defines the following constants to define some standard priorities
Thread scheduler uses this priorities while allocating CPU
The thread which having highest priority will get chance first.
If two thread having same priority then we can't expect exact execution order, it depends on thread scheduler.
The default priority only for the main thread is 5, but for all the remaining threads it will be inheriting from the parent, i.e., whatever the priority parent has the same priority will be inheriting to the child. Thread class defines the following two methods to get and set priority of a thread
public final int getPriority( );
public final void setPriority(int p);
The allowed values will be 1 to 10, otherwise we will get IllegalArgumentException
t.setPriority(1);
t.setPriority(10);
we can prevent thread from execution by using the followings methods.
yield( ) - To pause current executing thread for giving the chance to remaining waiting threads of same priority. if there are no waiting threads or all threads have low priority then same thread will continue it's execution once again.
Signature : public static native void yield( )
join( ) - If a thread wants to wait until completing some other threads then we should go for join( ) method. If thread t1 executes and t2.join( ) then t1 thread will enter into waiting state until t2 completes. once t2 completes then t1 will continue executes it's execution.
Join( ) method is overloaded and every join( ) throws Interrupted Exception. hence, whenever we are using join() we have to handle InterruptedException, either by try catch or by throws. otherwise we will get compile time error.
sleep( ) - If a thread don't want to perform any operation for a particular amount of time then we should use sleep( )
Whenever we are using sleep( ) we have to handle InterruptedException, otherwise we will get compile time error.
static: sleep method calls Thread.sleep( ) means class name t.start( ); t is object, so it is instance or non static
Note: A thread can interrupt another sleeping or waiting thread for this Thread class defines interrupt( ) method. public void interrupt( )
yield( )
join( )
sleep( )
Note: Class Level and block level both are different, there is no link between class level and block level. both are independent to each other.
The main advantage of synchronized block over synchronized method, it reduces the waiting time of the threads and improves the performance of system.
If two or more threads are waiting for same resources such type of situation is called deadlock, there is no resolution for deadlock but we have several prevention techniques. Synchronized keyword is the only reason for deadlock occurrence.
The threads which are executing in the background known as Daemon Thread eg. Garbage Collector. the main objective of daemon thread is to provide support for non daemon threads, we can check whether the thread is daemon or not by using Daemon( ) method. public final boolean isDaemon( )
We can change daemon nature of a thread by using setDaemon( ) method, but before starting the thread. public final void setDaemon(boolean b)
main thread is always non daemon and it is not possible to change it's daemon nature.