user3308901
user3308901

Reputation: 31

Thread Priority is not working

Main thread has priority 5, newly created thread has the priority same as main thread like 5. But before start the thread, I changed the priority of the newly created thread to 10. Highest priority thread need to execute first, but it not occuring like that, main thread is executing first. Please tell why and what is the wrong in my code, I pasted the total code and output. please help me.

public class MyThread1 extends Thread{

    @Override
    public void run(){

        System.out.println("Child Thread............");

         for(int i=1;i<10;i++){

            System.out.println("Child Thread");

        }
    }
}

public class ThreadMain {

    public static void main(String ar[]){

        int mainPriority=Thread.currentThread().getPriority();

        System.out.println("mainPriority = " + mainPriority);

        MyThread1 t1=new MyThread1();

        t1.setPriority(10);

        t1.start();

        int childPriority=t1.getPriority();

        System.out.println("childPriority = " + childPriority);

        for(int i=1;i<10;i++){

            System.out.println("Main Thread");

        }

    }

}

And the output is as follows why?

mainPriority = 5

childPriority = 10

Main Thread

Main Thread

Main Thread

Main Thread

Main Thread

Main Thread

Main Thread

Main Thread

Main Thread

Child Thread............

Child Thread

Child Thread

Child Thread

Child Thread

Child Thread

Child Thread

Child Thread

Child Thread

Child Thread

Can anybody help, thank you

Upvotes: 0

Views: 85

Answers (2)

Udara S.S Liyanage
Udara S.S Liyanage

Reputation: 6453

There is no thing like thread with the most priority executed first.

Upvotes: 0

TheLostMind
TheLostMind

Reputation: 36304

Thread priority is merely a suggestion / request to the underlying OS (scheduler) saying - Could you please run this thread with higher priority?. The OS might just decide to ignore your request

Upvotes: 1

Related Questions