Priorities and scheduling

Thread Priorities

Every thread has a priority that helps the operating system determine the order in which threads are scheduled for execution. In java thread priority ranges between,
  • MIN-PRIORITY (a constant of 1)
  • MAX-PRIORITY (a constant of 10)
By default every thread is given a NORM-PRIORITY(5). The main thread always have NORM-PRIORITY.

Thread Class

Thread class is the main class on which Java's Multithreading system is based. Thread class, along with its companion interface Runnable will be used to create and run threads for utilizing Multithreading feature of Java.

Constructors of Thread class

  1. Thread ( )
  2. Thread ( String str )
  3. Thread ( Runnable r )
  4. Thread ( Runnable rString str)
You can create new thread, either by extending Thread class or by implementing Runnable interface. Thread class also defines many methods for managing threads. Some of them are,

MethodDescription
setName()to give thread a name
getName()return thread's name
getPriority()return thread's priority
isAlive()checks if thread is still running or not
join()Wait for a thread to end
run()Entry point for a thread
sleep()suspend thread for a specified time
start()start a thread by calling run() method

Some Important points to Remember

  1. When we extend Thread class, we cannot override setName() and getName() functions, because they are declared final in Thread class.
  2. While using sleep(), always handle the exception it throws.
    static void sleep(long milliseconds) throws InterruptedException

No comments:

Post a Comment