Java Thread interrupt a thread

Introduction

The Thread class has an attribute that stores a boolean value indicating whether the thread has been interrupted or not.

When you call the interrupt() method of a thread, you set that attribute to true.

The isInterrupted() method only returns the value of that attribute.

class Timer extends Thread {
  public void run() {
    while (true) {
      System.out.println("Timer running. Date & time: " + new java.util.Date());
      try {/*from   w  ww. j  a  v  a2 s  . c o m*/
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        System.out.println("Timer was interrupted");
        return;
      }
    }
  }
}

public class Main {
  public static void main(String args[]) throws InterruptedException {
    Timer t = new Timer();
    t.start();
    Thread.sleep(4000);
    t.interrupt();
  }
}
import java.util.concurrent.TimeUnit;
/**// ww w. j ava2 s  .  c o  m
 *  Main class of the sample. Launch the PrimeGenerator, waits 
 *  five seconds and interrupts the Thread
 */
public class Main {
  public static void main(String[] args) {
    // Launch the prime numbers generator
    Thread task=new PrimeGenerator();
    task.start();
    
    // Wait 5 seconds
    try {
      TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    
    // Interrupt the prime number generator
    task.interrupt();
  }
}

class PrimeGenerator extends Thread{
  @Override
  public void run() {
    long number=1L;
    
    // This bucle never ends... until is interrupted
    while (true) {
      if (isPrime(number)) {
        System.out.printf("Number %d is Prime\n",number);
      }
      
      // When is interrupted, write a message and ends
      if (isInterrupted()) {
        System.out.printf("The Prime Generator has been Interrupted\n");
        return;
      }
      number++;
    }
  }

  /**
   *  Method that calculate if a number is prime or not
   * @param number : The number
   * @return A boolean value. True if the number is prime, false if not.
   */
  private boolean isPrime(long number) {
    if (number <=2) {
      return true;
    }
    for (long i=2; i<number; i++){
      if ((number % i)==0) {
        return false;
      }
    }
    return true;
  }

}



PreviousNext

Related