Skip to content

Instantly share code, notes, and snippets.

@paullewallencom
Created June 7, 2018 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paullewallencom/b819f0c5b88ffb46844cbf9553639747 to your computer and use it in GitHub Desktop.
Save paullewallencom/b819f0c5b88ffb46844cbf9553639747 to your computer and use it in GitHub Desktop.
Interrupting a thread
// Interrupting a thread
import java.util.concurrent.TimeUnit;
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();
// Write information about the status of the Thread
System.out.printf("Main: Status of the Thread: %s\n", task.getState());
System.out.printf("Main: isInterrupted: %s\n", task.isInterrupted());
System.out.printf("Main: isAlive: %s\n", task.isAlive());
}
}
public 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++;
}
}
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment