Hussein Jaber
Hussein Jaber

Reputation: 61

Do threads work with respect to their respective priority number?

Why would the compiler print 2 a and then 2 b or vice versa when giving the priority to Thread a to start? Shouldn't thread b wait for thread a to finish in order to start? Can someone please explain how does it work?

public class Test1 extends Thread{
    static int x = 0;
    String name;

    Test1(String n) {
      name = n;
    }

    public void increment() {
        x = x+1;
        System.out.println(x + " " + name);
    }

    public void run() {
        this.increment();
    }
}

public class Main {
    public static void main(String args[]) {
        Test1 a = new Test1("a");
        Test1 b = new Test1("b");
        a.setPriority(3);
        b.setPriority(2);
        a.start();
        b.start();
    }
}

Upvotes: 2

Views: 704

Answers (3)

Solomon Slow
Solomon Slow

Reputation: 27210

Why would the compiler print 2 a and then 2 b?

Luck of the draw. "Priority" means different things on different operating systems, but in general, it's always part of how the OS decides which thread gets to run and which one must wait when there's not enough CPUs available to run them both at the same time. If you computer has two or more idle CPUs when you start that program, then everybody gets to run. Priority doesn't matter in that case, and its just a race to see which one gets to the println(...) call first.

The a thread in your example has an advantage because the program doesn't call b.start() until after the a.start() method returns, but how big that advantage actually is depends on the details of the OS thread scheduling algorithm. The a thread could get a huge head start (like, it actually finishes before b even starts), or it could be a near-trivial head start.

Upvotes: 1

Nick
Nick

Reputation: 5042

Giving priorities is not a job for the compiler. It is the OS scheduler to schedule and give CPU time (called quantum) to threads.

The scheduler further tries to run as much threads at once as possible, based on the available number of CPUs. In today's multicore systems, more often than not more than one core are available.

If you want for a thread to wait for another one, use some synchronizing mechanism.

Upvotes: 3

Sockenpuppe
Sockenpuppe

Reputation: 1

Shouldn't thread b wait for thread a to finish in order to start?

No. The priority does not block the thread execution. It only tells the JVM to execute the thread "in preference to threads with lower priority". This does imply a wait.

Since your code is so trivial, there is nothing to wait for. Any of the two threads is run.

Upvotes: 3

Related Questions