Setting thread priorities


Setting a threads priority can be very useful if one thread has more critical tasks to perform than another.
The Thread class has a method called setPriority(int level) with which you can alter the priority a Thread instance has.
The priority level range from 1 (least important) to 10 (most important) and if no level is explicitly set, a Thread instance has the priority level of 5.
In the first example below no priorites are set, so both threads have the priority level 5. The TestThread class implements the Runnable interface and in its
run() method loops from 1 to 10 and output the number along with its Thread id, which is passed to the constructor.


/**
 * Main.java
 *
 * @author www.javadb.com
 */

public class Main {
    
    /**
     * Starts two threads and wait for them to finish.
     */

    public void setPrioritiesOnThreads() {
        
        Thread thread1 = new Thread(new TestThread(1));
        Thread thread2 = new Thread(new TestThread(2));
        
        thread1.start();
        thread2.start();
        
        try {
            
            //Wait for the threads to finish
            thread1.join();
            thread2.join();
            
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        
        System.out.println("Done.");
        
        
    }
    /**
     * Starts the program
     *
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        new Main().setPrioritiesOnThreads();
    }
    
    
    class TestThread implements Runnable {
        
        int id;
        
        public TestThread(int id) {
            
            this.id = id;
        }
        
        public void run() {
            
            for (int i = 1; i <= 10; i++) {
                System.out.println("Thread" + id + ": " + i);
            }
        }
    }
}


Since both threads have the same priority, the output will be a mix between them and could look like this:


Thread2: 1
Thread1: 1
Thread2: 2
Thread1: 2
Thread2: 3
Thread1: 3
Thread2: 4
Thread1: 4
Thread2: 5
Thread1: 5
Thread2: 6
Thread1: 6
Thread2: 7
Thread2: 8
Thread2: 9
Thread2: 10
Thread1: 7
Thread1: 8
Thread1: 9
Thread1: 10
Done.


The output could look different from on execution to another since we have no control of how the CPU will prioritize them.

If we set the priority on the threads we still haven't got exact control of the execution, but at least we can tell the CPU which one we think is
most important. The next example is identical to the one above except for the lines where the priority of the threads are set:


/**
 * Main.java
 *
 * @author www.javadb.com
 */

public class Main {
    
    /**
     * Starts two threads, setting priorities on them
     * and wait for them to finish.
     *
     */

    public void setPrioritiesOnThreads() {
        
        Thread thread1 = new Thread(new TestThread(1));
        Thread thread2 = new Thread(new TestThread(2));
        
        //Setting priorities on the Thread objects
        thread1.setPriority(Thread.MAX_PRIORITY);
        thread2.setPriority(Thread.MIN_PRIORITY);
        
        thread1.start();
        thread2.start();
        
        try {
            
            //Wait for the threads to finish
            thread1.join();
            thread2.join();
            
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        
        System.out.println("Done.");
        
        
    }
    /**
     * Starts the program
     *
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        new Main().setPrioritiesOnThreads();
    }
    
    
    class TestThread implements Runnable {
        
        int id;
        
        public TestThread(int id) {
            
            this.id = id;
        }
        
        public void run() {
            
            for (int i = 1; i <= 10; i++) {
                System.out.println("Thread" + id + ": " + i);
            }
        }
    }
}


The output from the code looked like this when executed:


Thread1: 1
Thread1: 2
Thread1: 3
Thread1: 4
Thread1: 5
Thread1: 6
Thread1: 7
Thread1: 8
Thread1: 9
Thread1: 10
Thread2: 1
Thread2: 2
Thread2: 3
Thread2: 4
Thread2: 5
Thread2: 6
Thread2: 7
Thread2: 8
Thread2: 9
Thread2: 10
Done.


It is however not certain that the first thread will be prioritized to finish before the second thread starts every time.
It is, as mentioned earlier, up to the CPU to decide.

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: