Search code examples
javamultithreadingschedulerthread-priority

Threading: Max priority thread does not always completed first


class A extends Thread {
    public void run() {
        for (int i = 1; i < 5; i++) {
            System.out.println("Thread A Loop NO " + i);

        }
        System.out.println("Exit from A");
    }
}

class B extends Thread {
    public void run() {
        for (int j = 1; j < 5; j++) {
            System.out.println("Thread B Loop no. " + j);
        }
        System.out.println("Exit from B");
    }
}

class C extends Thread {
    public void run() {
        for (int k = 1; k < 5; k++) {
            System.out.println("Thread C Loop no " + k);
        }
        System.out.println("Exit Form c");
    }
}

class Demo1 {
    public static void main(String args[]) {
        A a1 = new A();
        B b1 = new B();
        C c1 = new C();

        c1.setPriority(Thread.MAX_PRIORITY);
        a1.start();
        b1.start();
        c1.start();
    }
}  

I ran this program several times. Sometimes the thread "C" with max priority completes at the last Does the max priority not ensure it to terminate first? I mean before any other thread exits from the loop? If not what is the scheduler policy?


Solution

  • Does the max priority doesnot ensure it to terminate first????, i mean befor any other thread exits from the loop???

    No, It doesn't ensure anything.

    if not what is the scheduler policy???

    Its a hint to the OS which it is free to ignore esp if you are not a privileged user.

    Even if it did do what you suggest its a bad idea to depend on itself behaviour too much. i.e. I would always make sure your program behaves correctly without it.

    If you want Thread C to complete first you should run it first e.g. with c1.run();