Saturday 29 June 2019

Thread Priorities

  • Every Thread in java has some priority. It may be default priority generated by JVM (or) customized priority provided by the programmer.
  • The valid range of Thread priorities is 1 to 10[but not 0 to 10] where 1 is the least priority and 10 is highest priority.
  • Thread class defines the following constants to represent some standard priorities. 
                  1. Thread. MIN_PRIORITY    1
                  2. Thread. MAX_PRIORITY    10
                  3. Thread. NORM_PRIORITY    5
  • There are no constants like Thread.LOW_PRIORITY, Thread.HIGH_PRIORITY
  • Thread scheduler uses these priorities while allocating CPU(Processor).
  • The Thread which is having highest priority will get chance for first execution.
  • If 2 Threads having the same priority then we can't expect exact execution order it depends on Thread scheduler.
  • Thread class defines the following methods to get and set the priority of a Thread.
             1. public final int getPriority()
             2. public final void setPriority(int newPriority);//the allowed values are 1 to 10
  • The allowed values are 1 to 10 otherwise we will get runtime exception saying "IllegalArgumentException".
Example:
t.setPriority(8);//valid
t.setPriority(18);//IllegalArgumentException

Default priority:
  • The default priority only for the main Thread is 5. But for all the remaining Threads the default priority will be inheriting from parent to child. That is whatever the priority parent has by default the same priority will be for the child also.
Example 1:
class MyThread extends Thread
{}
class ThreadPriorityDemo
{
              public static void main(String[] args)
              {
                             System.out.println(Thread.currentThread().getPriority());//5
                             Thread.currentThread().setPriority(9);
                             MyThread t=new MyThread();
                             System.out.println(t.getPriority());//9
              }
}
 

 Example 2:
class MyThread extends Thread
{
              public void run()
              {
                             for(int i=0;i<10;i++)
                             {
                                           System.out.println("child thread");
                             }
              }
}
class ThreadPriorityDemo
{
              public static void main(String[] args)
              {
                             MyThread t=new MyThread();
                             //t.setPriority(10);          //----> 1 t.start();
                             for(int i=0;i<10;i++)
                             {
                                           System.out.println("main thread");
                             }
              }
}
 
  • If we are commenting line 1 then both main and child Threads will have the same priority and hence we can't expect exact execution order.
  • If we are not commenting line 1 then child Thread has the priority 10 and main Thread has the priority 5 hence child Thread will get chance for execution and after completing child Thread main Thread will get the chance in this the output is:
 Output:child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
  • Some operating systems(like windowsXP) may not provide proper support for Thread priorities. We have to install separate bats provided by vendor to provide support for priorities.

Thanks..!!

Getting and setting name of a Thread

  • Every Thread in java has some name it may be provided explicitly by the programmer or automatically generated by JVM.
  • Thread class defines the following methods to get and set name of a Thread.
Methods:
  1. public final String getName()
  2. public final void setName(String name)
Example: 


class MyThread extends Thread
{}
class ThreadDemo
{
              public static void main(String[] args)
              {
                             System.out.println(Thread.currentThread().getName());//main
                             MyThread t=new MyThread();
                             System.out.println(t.getName());//Thread-0
                             Thread.currentThread().setName("PKN Thread");

                             System.out.println(Thread.currentThread().getName());//PKN Thread
              }
}


Note: We can get current executing Thread object reference by using Thread.currentThread() method.


Thanks..!!

Thread class Constructors and Methods

The below are the constructors in java.lang.Thread class.
  • Thread t = new Thread(); //This allocates a new Thread object.
  • Thread t = new Thread(Runnable r); //This allocates a new Thread object.
  • Thread t = new Thread(String name); //This allocates a new Thread object.
  • Thread t = new Thread(Runnable r, String name); //This constructs allocates a new Thread object.
  • Thread t = new Thread(ThreadGroup g, String name); //This allocates a new Thread object.
  • Thread t = new Thread(ThreadGroup g, Runnable r); //This allocates a new Thread object.
  • Thread t = new Thread(ThreadGroup g, Runnable r, String name); //This allocates a new Thread object so that it has target as its run object, has the specified name as its name, and belongs to the thread group referred to by group.
  • Thread t = new Thread(ThreadGroup g, Runnable r, String name, long stackSize); //This allocates a new Thread object so that it has target as its run object, has the specified name as its name, belongs to the thread group referred to by group, and has the specified stack size.
The below is the java.lang.Thread class declaration
           public class Thread
                extends Object
                       implements Runnable

 Methods:

Sl No
Method Name
Description
1
activeCount()

public static int activeCount()

java.lang.Thread.activeCount() : It returns an estimate of the number of active threads in the current thread’s thread group and its subgroups.
2
checkAccess()

public final void checkAccess()

java.lang.Thread.checkAccess() : It determines if the currently running thread has permission to modify this thread
3
clone()

protected Object clone() throws 
CloneNotSupportedException

java.lang.Thread.clone() : Throws CloneNotSupportedException as a Thread cannot be meaningfully cloned
4
currentThread()

public static Thread currentThread()

java.lang.Thread.currentThread() : This method returns a reference to the currently executing thread object.
5
dumpStack()

public static void dumpStack()

java.lang.Thread.dumpStack() : This method prints a stack trace of the current thread to the standard error stream.
6
enumerate(Thread[] tarray)

public static int enumerate(Thread[] tarray)

java.lang.Thread.enumerate(Thread[] tarray) : This method copies into the specified array every active thread in the current thread’s thread group and its subgroups.
7
getAllStackTraces()

public static Map getAllStackTraces()
 
java.lang.Thread.getAllStackTraces() : This method returns a map of stack traces for all live threads.
8
getContextClassLoader()

public ClassLoader getContextClassLoader()

java.lang.Thread.getContextClassLoader() : This method returns the context ClassLoader for this Thread.
9
getDefaultUncaughtExceptionHandler()

public static Thread.UncaughtExceptionHandler 
getDefaultUncaughtExceptionHandler()
 
java.lang.Thread.getDefaultUncaughtExceptionHandler() : This method returns the default handler invoked when a thread abruptly terminates due to an uncaught exception.
10
getId()

public long getId()

java.lang.Thread.getId() : It returns the identifier of this Thread
11
getName()

public final String getName()
 
java.lang.Thread.getName() : This method returns this thread's name.
12
getPriority()

public final int getPriority()

java.lang.Thread.getPriority() : This method Returns this thread's priority.
13
getStackTrace()

public StackTraceElement[] getStackTrace()

java.lang.Thread.getStackTrace() : This method returns an array of stack trace elements representing the stack dump of this thread.
14
getState()

public Thread.State getState()

java.lang.Thread.getState() : It returns the state of this thread.
15
getThreadGroup()

public final ThreadGroup getThreadGroup()
 
java.lang.Thread.getThreadGroup() : It returns the thread group to which this thread belongs.
16
getUncaughtExceptionHandler()

public Thread.UncaughtExceptionHandler 
getUncaughtExceptionHandler()

java.lang.Thread.getUncaughtExceptionHandler() : It returns the handler invoked when this thread abruptly terminates due to an uncaught exception.
17
holdsLock(Object obj)

public static boolean holdsLock(Object obj)

java.lang.Thread.holdsLock(Object obj) : It returns true if and only if the current thread holds the monitor lock on the specified object.
18
interrupt()

public void interrupt() 

java.lang.Thread.interrupt() : Interrupts this thread.
19
interrupted()

public static boolean interrupted()

java.lang.Thread.interrupted() : Tests whether the current thread has been interrupted.
20
isAlive()

public final boolean isAlive()

java.lang.Thread.isAlive() : Tests if this thread is alive.
21
isDaemon()

public final boolean isDaemon()

java.lang.Thread.isDaemon() : Tests if this thread is a daemon thread.
22
isInterrupted()

public boolean isInterrupted()

java.lang.Thread.isInterrupted() : Tests whether this thread has been interrupted.
23
join()

public final void join() throws InterruptedException

java.lang.Thread.join() : It waits for this thread to die.
24
join(long millis)

public final void join(long millis) 
throws InterruptedException

java.lang.Thread.join(long millis) : It waits at most millis milliseconds for this thread to die.
25
run()

public void run()

java.lang.Thread.run() : If this thread was constructed using a separate Runnable run object, then that Runnable object’s run method is called; otherwise, this method does nothing and returns.
26
yield()

public static void yield()

java.lang.Thread.yield() : A hint to the scheduler that the current thread is willing to yield its current use of a processor.
27
toString()

public String toString()

java.lang.Thread.toString() : Returns a string representation of this thread, including the thread’s name, priority, and thread group.
28
start()

public void start()

java.lang.Thread.start() : Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
29
sleep(long millis)

public static void sleep(long millis) 
throws InterruptedException

java.lang.Thread.sleep(long millis) : Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
30
setUncaughtExceptionHandler(Thread.
UncaughtExceptionHandler eh)

public void setUncaughtExceptionHandler(
Thread.UncaughtExceptionHandler eh)

java.lang.Thread.setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) : Set the handler invoked when this thread abruptly terminates due to an uncaught exception.
31
setPriority(int newPriority)

public final void setPriority(int newPriority)

java.lang.Thread.setPriority(int newPriority) : Changes the priority of this thread.
32
setName(String name)

public final void setName(String name)

java.lang.Thread.setName(String name) : Changes the name of this thread to be equal to the argument name.
33
setDefaultUncaughtExceptionHandler(Thread.
UncaughtExceptionHandler eh)

public static void setDefault
UncaughtExceptionHandler
(Thread.UncaughtExceptionHandler eh)

java.lang.Thread.setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) : Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread.
34
setDaemon(boolean on)

public final void setDaemon(boolean on)

java.lang.Thread.setDaemon(boolean on) : Marks this thread as either a daemon thread or a user thread.
35
setContextClassLoader(ClassLoader cl)

public void setContextClassLoader
(ClassLoader cl)

java.lang.Thread.setContextClassLoader(ClassLoader cl) : Sets the context ClassLoader for this Thread.
  


Thanks..!!