How can a Thread preempt another Thread?

Brandon Rohlfs

Any Threads running within the JVM can be preempted by creating and starting a Thread which is of a higher priority. A Threads priority can be set using the following method.

public void setPriority(int newPriority) 

Below is a short example of how preemption works. Two Threads are created and started both of which have a default priority of five. A third Thread is created with a higher priority than both previously created Threads. Since each Thread executes a small amount of time preemption will probably not occur but eventually the Thread Schedular will cease all currently running Threads with a lower priority.

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"); 
  t3.setPriority(Thread.currentThread().getPriority() + 1); 

class T implements Runnable{
 private int square; 

 public void run(){
  for(int i = 1; i < 50; i++){
   square = i * i; 
   System.out.println("Thread " + Thread.currentThread().getName() +
	" has a priority of " + Thread.currentThread().getPriority() +
	 ": " + square);