0

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

piet.t
  • 11,718
  • 21
  • 43
  • 52
user3308901
  • 31
  • 2
  • 4
  • possible duplicate of [Java Thread priority has no effect](http://stackoverflow.com/questions/12038592/java-thread-priority-has-no-effect) – Raedwald Sep 03 '14 at 06:56

2 Answers2

1

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

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • Actually, it's not even that. Java "priority" will translate to a scheduling "weight" on most desktop/laptop/tablet/phone operating systems. Scheduling weight influences how much CPU time the thread gets when it competes for CPU against other threads. The OS continually adjusts the true scheduling priorities according to the thread's weights, and how much CPU they recently have used. – Solomon Slow Sep 03 '14 at 13:44
0

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

Udara S.S Liyanage
  • 6,189
  • 9
  • 33
  • 34