简体   繁体   中英

Priorities set on thread has no effect when start is called on the thread object

I executed below code :

public class TestMain extends Thread{

    public static Runnable getRunnableObject(){
        Runnable r = new Runnable(){
            @Override
            public void run() {
                System.out.println("inside runnable");
            }
        };

        return r;           
    }

    public static void main(String args[]){
        Thread t2 = new Thread(getRunnableObject());
    //  t2.start();
        System.out.println("name "+t2.getName()+" id "+t2.getPriority()+" class "+t2.getClass()
                +" priortity "+t2.getPriority()+" state "+t2.getState()+" alive/dead "+t2.isAlive());

        System.out.println("runtime"+Runtime.getRuntime().availableProcessors());
        t2.setPriority(MAX_PRIORITY);
        System.out.println(t2.getPriority());

        t2.setPriority(MIN_PRIORITY);
        System.out.println(t2.getPriority());

        t2.setPriority(NORM_PRIORITY);
        System.out.println(t2.getPriority());
    }
}

Output :

name Thread-0 id 5 class class java.lang.Thread priortity 5 state NEW alive/dead false
runtime4
10
1
5

Now I run it once again uncommenting the code at line 22.

output 2 :

inside runnable
name Thread-0 id 5 class class java.lang.Thread priortity 5 state RUNNABLE alive/dead true
runtime4
5
5
5

Can you tell me why setting the priority is not working when I called start() on the thread ?

It's a race condition.

By the time you're trying to set the priority of t2 , it's already dead. If you change your Runnable to block for a while, like this:

Runnable r = new Runnable() {

    @Override
    public void run() {
        System.out.println("inside runnable");
        try {
            Thread.sleep(100000);
        } catch (InterruptedException e) {
           //
        }
    }
}

Then you'll get the same sequence of 10, 1, 5.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM