Thread Scheduler
The thread scheduler is responsible for
managing the execution of threads. The Java Virtual Machine (JVM) employs a
preemptive, priority-based scheduling algorithm to determine which thread
should run next. Threads with higher priority are scheduled to run before
threads with lower priority.
Example 01:
package com.java.Multi_threading;
class MyThread extends Thread {
public MyThread(String name) {
super(name); // Set the thread name
}
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(getName() + " - Priority: " + getPriority() + " - Count: " + i);
try {
Thread.sleep(100); // Sleep to simulate work and allow context switching
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadSchedulerExample {
public static void main(String[] args) {
// Create three threads with different priorities
MyThread t1 = new MyThread("Thread-1 (Low Priority)");
MyThread t2 = new MyThread("Thread-2 (High Priority)");
MyThread t3 = new MyThread("Thread-3 (Medium Priority)");
// Set thread priorities
t1.setPriority(Thread.MIN_PRIORITY); // Priority 1
t2.setPriority(Thread.MAX_PRIORITY); // Priority 10
t3.setPriority(Thread.NORM_PRIORITY); // Priority 5
// Start the threads
t1.start();
t2.start();
t3.start();
}
}
0 Comments