Threads. Preemption not working.
Once T3 starts it should run to completion with all current running threads yielding until then. This does not seem to be the case though. Any ideas why??? Thanks.
Code:
public class PreemptTest{
public static void main(String[] args){
Thread t1 = new Thread(new T(), "t1");
Thread t2 = new Thread(new T(), "t2");
Thread t3 = new Thread(new T(), "t3");
t1.start();
t2.start();
t3.setPriority(Thread.currentThread().getPriority() + 1);
t3.start();
}
}
class T implements Runnable{
private int square;
public void run(){
for(int i = 1; i < 5; i++){
square = i * i;
System.out.println("Thread " + Thread.currentThread().getName() +
" has a priority of " + Thread.currentThread().getPriority() +
": " + square);
}
}
}
Re: Threads. Preemption not working.
I am assuming if the execution of the threads was long enough preemption would take place. Im my case my threads only execute a short amount of time.
Re: Threads. Preemption not working.
Let's see.
Option 1: your threads run so shortly that they finish within a single time slice, before the next one is even started.
Option 2: the scheduler implements some sort of "fair" mechanism that temporarily raises a thread's importance if it hasn't run for some time.
Re: Threads. Preemption not working.
Probably option one. I tried the code with a larger loop and it seems the third Thread eventually prempts the other two.