javamultithreadingthread-priority

Do threads work with respect to their respective priority number?


Why would the compiler print 2 a and then 2 b or vice versa when giving the priority to Thread a to start? Shouldn't thread b wait for thread a to finish in order to start? Can someone please explain how does it work?

public class Test1 extends Thread{
    static int x = 0;
    String name;

    Test1(String n) {
      name = n;
    }

    public void increment() {
        x = x+1;
        System.out.println(x + " " + name);
    }

    public void run() {
        this.increment();
    }
}

public class Main {
    public static void main(String args[]) {
        Test1 a = new Test1("a");
        Test1 b = new Test1("b");
        a.setPriority(3);
        b.setPriority(2);
        a.start();
        b.start();
    }
}

Solution

  • Giving priorities is not a job for the compiler. It is the OS scheduler to schedule and give CPU time (called quantum) to threads.

    The scheduler further tries to run as much threads at once as possible, based on the available number of CPUs. In today's multicore systems, more often than not more than one core are available.

    If you want for a thread to wait for another one, use some synchronizing mechanism.