How to do it...

Follow these steps to implement the example:

  1. Create a class called PrimeGenerator that extends the Thread class:
        public class PrimeGenerator extends Thread{
  1. Override the run() method including a loop that will run indefinitely. In this loop, process consecutive numbers beginning from one. For each number, calculate whether it's a prime number; if yes, as in this case, write it to the console:
        @Override 
public void run() {
long number=1L;
while (true) {
if (isPrime(number)) {
System.out.printf("Number %d is Prime ",number);
}
  1. After processing a number, check whether the thread has been interrupted by calling the isInterrupted() method. If this method returns true, the thread has been interrupted. In this case, we write a message in the console and end the execution of the thread:
            if (isInterrupted()) { 
System.out.printf("The Prime Generator has been
Interrupted");
return;
}
number++;
}
}
  1. Implement the isPrime() method. You can get its code from the Creating, running, and setting information of a thread recipe of this chapter.
  2. Now implement the main class of the example by implementing a class called Main and the main() method:
        public class Main { 
public static void main(String[] args) {
  1. Create and start an object of the PrimeGenerator class:
        Thread task=new PrimeGenerator(); 
task.start();
  1. Wait for 5 seconds and interrupt the PrimeGenerator thread:
        try { 
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
task.interrupt();
  1. Then, write information related to the status of the interrupted thread. The output of this piece of code will depend on whether the thread ends its execution before or after:
          System.out.printf("Main: Status of the Thread: %s
",
task.getState());
System.out.printf("Main: isInterrupted: %s ",
task.isInterrupted());
System.out.printf("Main: isAlive: %s ", task.isAlive());
}
  1. Run the example and see the results.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.42.171