Thread Priorities and thread methods in Multithreading Java

Thread Priorities

Every thread has priority either given by JVM or by user Thread priorities ranges from 1-10.

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

Thread.MIN_PRIORITY->1

Thread.MAX_PRIORITY->10

Thread.NORMAL_PRIORITY->5

If two thread have same priority then we cant expect exact execution order. It depends on thread scheduler.
  • Public final int getPriority()
  • Public final void setPriority(int p)
Allowed values range from 1-10
Any other value-> run-time exception (Illegal argument exception)
Default priority is only for main thread, i.e .5 where as all remaining threads default priority will be inherited from parent to child.
class MyThread extends Thread {
}public class Demo1 { 
public static void main(String[] args) 
{
 System.out.println(Thread.currentThread().getPriority());
 MyThread t = new MyThread();
Thread.currentThread().setPriority(7);
System.out.println(Thread.currentThread().getPriority());
//Thread.currentThread().setPriority(13); 
//System.out.println(Thread.currentThread().getPriority());
 }
 }
Some platform wont support priority:
class MyThread extends Thread
 { 
public void run(){ for(int i=0; i<3; i++)
 { 
System.out.println("Child Thread"); 
}
 } 
}
public class Demo1
 { 
public static void main(String[] args)
 { 
MyThread t = new MyThread();
 t.setPriority(10); 
t.start(); 
for(int i=0; i<3; i++)
 { 
System.out.println("Main Thread"); 
}
}
}
In How many ways we can stop/prevent thread execution?
1. Yield()
2. Join()
3. Sleep()
1. Yield(): Works as FCFS (First come first serve), yield method cause to pause current executing thread and gives chance to same priority. If in case no waiting threads/all waiting threads have low priority then same thread is allowed to continue.
If multiple threads are waiting with same priority then which waiting thread will get a chance can’t be expected, then it depends on thread scheduler. The thread which is yielded, when it will get chance again depends on threadscheduler and we can’t expect exact output.
class MyThread extends Thread
 { 
public void run(){ for(int i=0; i<3; i++) 
{ 
System.out.println("Child Thread"); 
Thread.yield();
 }
 }
 }
public class Demo1 
{
 public static void main(String[] args) 
{ 
 MyThread t = new MyThread();
 t.start(); for(int i=0; i<3; i++) 
{
 System.out.println("Main Thread");
 }
}
}
In the above program if we are commenting line 1 then both threads are executing simultaneously and we cant expect which thread completes execution first, else child thread always calls yield() where main thread will have chance to get execute first.
2. join(): If a thread wants to wait until completion of some other thread then we should go for join.
  • public final void join()
  • public final void join(long ms)
  • public final void join(long ms, int ns)
Every join () throws Interrupted exception which checked exception-> we should handle either by try catch or throws method else will get compilation error.
Case: 1
class MyThread extends Thread 
{
 public void run()
{ 
for(int i=1;i<=5;i++)
{ 
try
{
 Thread.sleep(2000); 
}
catch(Exception e)
{
System.out.println(e);
} 
System.out.println(i);
 }
 }
 }
 public class Demo1
 { 
public static void main(String[] args) throws InterruptedException 
{ 
MyThread t = new MyThread(); 
MyThread t1=new MyThread();
 t.start(); try{ t.join(1000); 
}
catch(Exception e)
{
System.out.println(e);
}
 t1.start(); 
}
}
Case2: Waiting of child thread until completion of main thread
class MyThread extends Thread 
{
 static Thread mt; public void run()
{
 try
{
mt.join();
 }
catch(Exception e){System.out.println(e);
}
 for(int i=1;i<=5;i++)
{ 
System.out.println(i);
 }
 }
} 
public class Demo1
 {
 public static void main(String[] args) throws InterruptedException
 { 
MyThread.mt= Thread.currentThread();
 MyThread mt = new MyThread(); mt.start(); 
// mt.join();
 for(int i=0;i<5;i++)
 {
 System.out.println("MAin Thread");
 Thread.sleep(1000);
 }
 }
 }
In the above program, child thread calls join Method on main thread, hence thread has to wait until the main thread completes
Case3: If main thread calls join on main thread object and child thread calls join() then both threads will wait forever. And program will be stuck (Dead lock situation)
Case4: If a thread calls join() on same thread itself then program will be stuck or deadlock situation occurs// as to wait infinite times.
3. Sleep(): If a thread doesn’t want to perform any operation for particular amount of time then thread should go for sleep()
  • public static native void sleep(long ms)
  • public static void sleep(long ms, int ns)
Every sleep() throws Interrupted exception, its mandatory to handle that by try catch/throws else we will get compile time error.
public class SlideRotator {
public static void main(String[] args) throws InterruptedException 
{
 for(int i=0; i<4;i++) 
{ 
System.out.println("Slide-"+i); 
Thread.sleep(5000); 
}
}
}
How a thread can interrupted another thread
Public void interrupt(): only we can use for sleeping thread or waiting thread
class MyThreads extends Thread
{
 public void run() 
{
 try{ 
for(int i=0;i<5;i++) 
{ 
System.out.println("I'M LAZY THREAD"); 
Thread.sleep(2000); 
}
}catch(InterruptedException e)
{ 
System.out.println("I got Interrupted");
} 
} 
}
public class ThreadInterruptDemo
 { 
public static void main(String[] args) 
{ 
MyThreads mt= new MyThreads(); 
mt.start(); mt.interrupt();//line1 
System.out.println("Main Thread"); 
}
}
If we comment line1 main thread wont interrupt child thread and it is executed 5 times
class MyThreads extends Thread
{ 
public void run()
{ 
for(int i=0;i<5;i++)
 {
 System.out.println("I'M LAZY THREAD");
 }
 System.out.println("I Want To Sleep"); 
try{ 
Thread.sleep(2000);
 } catch(InterruptedException e)
{
 System.out.println("I got Interrupted");
} 
}
}
Note: Whenever we are calling interrupt thread and target is not in sleep()/wait() then there is no impact of interrupt call immediately. Interrupt call will be be waited until the target is sleeping/waiting
If the target thread never entered into sleep()/wait() in its lifetime then there is no impact of interrupt call, this is only where interrupt call is waited, In the above example interrupt call waited until child thread computes for loop for 5 times.
activeCount(): It will return the no of threads which are in active.
public class ThreadInterruptDemo
 {
 public static void main(String[] args)
 {
MyThreads t=new MyThreads();
 t.start(); 
System.out.println(Thread.activeCount()); 
}
}

Posted on by