Java Program to get Name and priority of Thread.
Objective
Write a Java program to get and display the default name and priority of threads.
Algorithm / Approach
- Create a class extending
Threadwith an emptyrun()method. - In main, instantiate three thread objects.
- Use the
getName()method to retrieve the default name assigned by the JVM. - Use the
getPriority()method to retrieve the default priority level assigned by the JVM. - Print the results.
Test.java
class Test extends Thread {
public void run() {
System.out.print("Run Method");
}
}
class Demo{
public static void main(String[] a)
{
Test t = new Test();
Test t2 = new Test();
Test t3 = new Test();
System.out.print("Name: ");
System.out.println(t.getName());
System.out.print("Priority: ");
System.out.println(t.getPriority());
System.out.print("Name: ");
System.out.println(t2.getName());
System.out.print("Priority: ");
System.out.println(t2.getPriority());
System.out.print("Name: ");
System.out.println(t3.getName());
System.out.print("Priority: ");
System.out.println(t3.getPriority());
}
}
Expected Output
Name: Thread-0 Priority: 5 Name: Thread-1 Priority: 5 Name: Thread-2 Priority: 5
Explanation of the Program
- Every thread in Java is automatically given a name (e.g., Thread-0, Thread-1) and a priority by the JVM when it is created.
- Thread priorities dictate to the thread scheduler which threads should get CPU time first. The scale goes from 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY).
- By default, all user threads inherit a normal priority of 5 (NORM_PRIORITY) from the main thread. You can change this later using
setPriority().
Complexity
Time Complexity
O(1)
Space Complexity
O(1)