hello
i have a problem with Priority when I set priority of any thread then I get wrong output my code is below

class Run implements Runnable{

    private String st;

    public Run(String s){

        st=s;
    }

    public void run(){

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

            System.out.println(st+"="+i);
        }
    }
}

class PriorityCheck{

    public static void main(String ss[]){

        Run first=new Run("First");
        Run second=new Run("Second");

        Thread t1=new Thread(first);
        Thread t2=new Thread(second);

        t1.setPriority(Thread.MIN_PRIORITY);
        t2.setPriority(Thread.MAX_PRIORITY);

        t1.start();
        t2.start();
    }
}

and its output is below

First=1
Second=1
First=2
Second=2
First=3
Second=3
First=4
Second=4
First=5
Second=5
First=6
Second=6
First=7
Second=7
First=8
Second=8
First=9
Second=9
First=10
Second=10

but output should like this

Second=1
Second=2
Second=3
Second=4
Second=5
Second=6
Second=7
Second=8
Second=9
Second=10
First=1
First=2
First=3
First=4
First=5
First=6
First=7
First=8
First=9
First=10

please help me

Recommended Answers

All 9 Replies

Maybe your computer is capable of running two threads at the same time?

i think this is problem of priority scheduling algorithm how to fix it

What is the processor in your PC. Does it have 2 or more cores?

Even if the processor has a single core, newer Operating systems (not DOS for sure) employ preemptive scheduling which gives the "illusion" of threads running in parallel. Also, even if there is just a single core, the preemptive scheduling means that threads would run in "random" order as scheduled by the OS.

In short, one guaranteed way of printing your output would be to start up the first thread after your second thread is done. Or use synchronization primitives to ensure that first thread always "blocks" until the second one is complete.

EDIT: Also priority is just a "hint" to the OS and is interpreted in an OS specific way. There is "no guarantee" that a thread with higher priority will execute completely before giving way to a thread with lower priority. Read this

My Processor's configuration is below

Intel(R) Core(TM) i5 CPU M480 @ 2.67GHz 2.66GHz

In that case your system is perfectly capable of running multiple threads at exactly the same time (plus see ~s.o.s~ comments above).

can we set operating system priorities?????

Please read the information in the link at the end of ~s.o.s~ post.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.