Created
June 7, 2018 15:13
-
-
Save paullewallencom/b819f0c5b88ffb46844cbf9553639747 to your computer and use it in GitHub Desktop.
Interrupting a thread
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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