Connect with us

Multithreading

What is Thread Priority?

Every thread in java has some priority ,it may be default priority generated by JVM or customize priority provided by programmer. The valid range of thread priority is 1 to 10 where 1 is Min Priority and 10 is Max Priority.

Thread class defines the following constants to represent some statndards  priorities.

Thread.MIN_PRIORITY—>1

Thread.NORM_PRIORITY—>5

Thread.MAX_PRIORITY—->10

Thread scheduler will use priorities while allocating processor. The thread which is having highest priority will get the chance first.

If two threads having same priority then we cant expect exact execution order. It depends on Thread Scheduler.

Thread class define the following method to set and get the priority of a thread.

public final int getPriority();

public final void setPriority(ing p);

Allowed values range is 1 to 10 otherwise there will be a run time exception IllegalArgumentException caught.

 

How To Prevent Thread From Execution

 

We can preven a thread execution by using the folowwing methods:

1: yield()

2: join();

3: sleep()

 

yield() method causes to paus current executing thread to give the chance for waiting threads of same priority. If there is no waiting thread or all waiting threads have low priority then same thread can continue its execution.

if multiple threads are waiting with same priority then which waiting thread will get the chance we can’t expect and it depends on thread scheduler.

The thread which is yielded, we can’t expect exactly when it will get the chance  again because  it depends on thread scheduler.

Thread Scheduler

Note: Some plateform won’t provide proper support for yield method.

join() method in multithreading

If a thread wants to wait untill completing some other thread then we should go for join() method.

For example, if a thread t1 wants to wait until completing t2, then t1 has to call t2.join(). If t1 executes t2.join() then immedialtly t1 will be entered into waiting state untill t2 complets. Once t2 completes then t1 can continue its execution.

Lets take an analogy to understand the concept well.

Suppose there is a marriage activity & we have three task to complete

Task 1: Venue Fixing Activity

Task 2: Card Printing Activity

Task 3: Card distribution Activity.

It clear that  task2 has to wait untill Task1 completed & Task 3 has to wait until Task2 is completed. So, Tast 2 call join() method on Task1 & Task 3 has to call join() method on task2. 

 

 

join

Within Card Printing thread (t2) has to wait until venue fixing thread(t1) completion. Hence, t2 has to call t1.join().

Within Card Distribution thread(t3) has to wait untill card printing thread(t2) completion. Hence, t3 has to call t2.join().

public final void join() throws InterruptedException 


public final void join(long ms) throws InterruptedException 


public final void join(long ms,int ns) throws InterruptedException 

Every join() method  throws InterruptedException   which is checked exception. Hence, we must have to handle this exception either by using try catch or by throws keyword.

				
					
public class RunnableTest {

	public static void main(String[] args) {
		
		
		MThread t =new MThread();
		t.start();
	
		try {
			t.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
         for (int i = 1; i <= 5; i++) {
			
			System.out.println("Main Thread "+i);
			
		}

	}
		
}

class MThread extends Thread {
	
	@Override
	public void run() {
		
		for (int i = 1; i <= 5; i++) {
			
			System.out.println("Child Thread "+i);
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}

				
			
				
					Output:
Child Thread 1
Child Thread 2
Child Thread 3
Child Thread 4
Child Thread 5
Main Thread 1
Main Thread 2
Main Thread 3
Main Thread 4
Main Thread 5

				
			

sleep() method

If a Thread don’t want to perform any operation for a particular amount of time then we should go for sleep() method.


1. public static native void sleep(long ms) throws InterruptedException


2. public static void sleep(long ms,int ns)throws InterruptedException

What is deadlock in multithreading ?

If two threads are waiting for eachother forever such type of infinite waiting is called deadlock.

Synchronized keuword is the only reason for deadlock situation Hence, while using synchronized keyword , we have to take special care.

There are no resolution technique for deadlock but there are preventartion techniques are available.

If waiting ends at some point then this is called starvation. For example, low priority thread has to wait untill higher priority thread completed.

What is Deamon Thread?

The thread which are running in the background is called daemon thread.

For example:

1:Garbage Collector   2: SIgnal Dispatcher   3: Attach Listener  etc.

The main objective of daemon thread is to provide support for non daemon thread(Main Thread). For example, if main thread is runs with low memory then JVM runs Garbage Collector to destroy the useless object so that number of free memory is improved.

Usually daemon thread having low priority but based on our requirement , daemon thread can run high priority also.

Default Nature of Thread:

By default Main thread is non daemon and for all reamaining thread daemon nature will be inheritaed from Parent to Child that is if the parent thread is Daemon then automatically child thread is also daemon, and if the Parent thread is non daemon then automatically child thread is also non-daemon. 

Note: It is ompossible to change daemon nature of main thread because it is already started by JVM at begining.

When last non-daemon thred is terminates , automatically  all daemon thread will be terminated irrespective of their position.