The concept of priorities in threads states that each thread has a priority. In layman's terms, this means that each object has a priority, and the priority numbers range from 1 to 10.
Thread thread = new Thread(); int priority = thread.getPriority(); System.out.println("Thread priority: " + priority);
Thread thread = new Thread(); thread.setPriority(Thread.MAX_PRIORITY); // Sets the priority to the highest level (10)
public class ThreadPriorityExample { public static void main(String[] args) { Thread thread1 = new Thread(new MyRunnable()); Thread thread2 = new Thread(new MyRunnable()); // Set the priorities of the threads thread1.setPriority(Thread.MIN_PRIORITY); thread2.setPriority(Thread.MAX_PRIORITY); // Start the threads thread1.start(); thread2.start(); // Print the priorities of the threads System.out.println("Thread 1 priority: " + thread1.getPriority()); System.out.println("Thread 2 priority: " + thread2.getPriority()); } static class MyRunnable implements Runnable { @Override public void run() { for (int i = 1; i <= 5; i++) { System.out.println("Running Thread: " + Thread.currentThread().getName() + " with priority " + Thread.currentThread().getPriority()); } } } }
Output:
Running Thread: Thread-0 with priority 1
Running Thread: Thread-0 with priority 1
Running Thread: Thread-0 with priority 1
Running Thread: Thread-0 with priority 1
Running Thread: Thread-0 with priority 1
Running Thread: Thread-1 with priority 10
Running Thread: Thread-1 with priority 10
Running Thread: Thread-1 with priority 10
Running Thread: Thread-1 with priority 10
Running Thread: Thread-1 with priority 10
Thread 1 priority: 1
Thread 2 priority: 10
public class Main extends Thread{ public void run(){ System.out.println("Run method"); } public static void main(String[] args){ Thread.currentThread().setPriority(6);// The priority of the main thread is now set to 6. System.out.println("Priority of Main : "+ Thread.currentThread().getPriority()); Main thread1 = new Main(); // thread1 thread is child of main thread so thread1 thread will also have priority 6 System.out.println("Priority of thread1 : "+ thread1.getPriority()); } }
Output:
Priority of Main thread : 6
Priority of thread1 : 6
Police Colony
Patna, Bihar
India
Email:
Post your comment