La modification et l'obtention de la priorité d'une unité d'exécution s'effectuent en invoquant respectivement les méthodes setPriority() et getPriority().
// Affectation d'une nouvelle priorité de niveau 9. unThread.setPriority(9); // Récupération du niveau de priorité. int priorite = unThread.getPriority();
Si l'argument fourni à la méthode setPriority() n'est pas compris entre 1 et 10, une exception IllegalArgumentException risque d'être levée.
Dans une application multi-threads, les priorités doivent être distribuées d'une manière cohérentes. En général, il existe un thread prédominant et d'autres de plus ou moins grande importance. Le premier doit possèder la priorité la plus élevée par rapport aux autres threads.
Exemple [voir]public class Priorite extends Thread { private int temps; private int iterations; public static void main(String[] args) { Thread t1 = new Priorite(20, 50); Thread t2 = new Priorite(20, 50); Thread t3 = new Priorite(20, 50); t1.setName("Thread Priorite elevee"); t2.setName("Thread Priorite basse"); t3.setName("Thread Priorite normale"); t1.setPriority(Thread.MAX_PRIORITY); t2.setPriority(Thread.MIN_PRIORITY); t2.setPriority(Thread.NORM_PRIORITY); t1.start(); t2.start(); t3.start(); } public Priorite(int temps, int iterations) { this.temps = temps; this.iterations = iterations; } public void run() { for (int i = 0; i < iterations; i++) { System.out.println(this.getName() + " [" + this.getPriority() + "] : " + i); try { Thread.sleep(temps); } catch (InterruptedException e) { e.printStackTrace(); } } } }