Creating a Thread Part Three Tutorial

This tutorial will directly build on concepts and source code from my Creating a Thread Part One Tutorial and Creating a Thread Part Two Tutorial. In this tutorial I will demonstrate how to create multiple child threads using both versions of my custom prime-number-calculating class. I will also introduce you to a concept called thread safety. A method in Java is considered to be thread safe if it can be used by multiple threads without causing any problems. You will see how easy it is to get wrapped up in the power of multithreading without considering the side-effects of thread safety.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md CreatingAThreadone
C:\Java>cd CreatingAThreadone
C:\Java\CreatingAThreadone>Notepad CreatingAThreadone.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


import java.util.*;
class CreatingAThreadone {

    private static ArrayList<String> primeList = new ArrayList<>();
    static void addToList(String message) {
        primeList.add(message);
    }
    static ArrayList<String> getListReference() {
        return primeList;
    }


    public static void main(String args[]) {

        for (long x = 6223372036854775899L; x <= 6223372036854775999L; x+=2) {
            new Thread(new MyCalcRunnable(x)).start();
        }
        for (long x = 9223372036854775703L; x <= 9223372036854775789L; x+=2) {
            new MyCalcThread(x, "myChildThread"+x);
        }


        Thread mainThread = Thread.currentThread(); // main thread
        int spinner = 0;
        char animation = ' ';
        System.out.println("Total number of active threads: " + Thread.activeCount());
        System.out.print("Calculating primes: ");
        while(Thread.activeCount() > 1) {
            spinner++;
            switch(spinner) {
                case 1: 
                    animation = '|';
                    break;
                case 2: 
                    animation = '/';
                    break;
                case 3:
                    animation = '-';
                    break;
                case 4:
                    animation = '\\';
                    spinner = 0;
                    break;
            }
            System.out.print("\b"+animation);

            try {
                mainThread.sleep(200);
            } catch (InterruptedException e) {
                System.out.println("Main thread interrupted");
            }
        }
        System.out.println();
        ArrayList<String> filledList = CreatingAThreadone.getListReference();
        for (String s : filledList) {
            System.out.println(s);
        }
    }

}

class MyCalcThread extends Thread {
    private long numberToFactor = 0;

    MyCalcThread(long numberToFactor, String threadName){
        super(threadName);
        this.numberToFactor = numberToFactor;
        start();
    }

    @Override
    public void run() { // this is where the new thread starts
        CreatingAThreadone.addToList(new PrimeStuff().isItPrime(numberToFactor));
    }

}

class MyCalcRunnable implements Runnable {
    private long numberToFactor = 0;

    MyCalcRunnable(long numberToFactor){
        this.numberToFactor = numberToFactor;
    }

    @Override
    public void run() { // this is where the new thread starts
        CreatingAThreadone.addToList(new PrimeStuff().isItPrime(numberToFactor));
    }

}

class PrimeStuff {
     String isItPrime(long numberToFactor) { 
        if (numberToFactor % 2 == 0)
            return (numberToFactor + " is NOT Prime ... divisible by 2");

        long squareRoot = (long) Math.sqrt(numberToFactor);
        for (long i = 3; i <= squareRoot; i+=2) {
            if (numberToFactor % i == 0) { // when the remainder is 0 the number is evenly divisible - hence not prime
                return (numberToFactor + " is NOT Prime ... first divisible by " + i);
            }
        }
        return (numberToFactor + " is Prime!!!");
    }    
}


Now switch back to the command prompt (CMD) and type in javac CreatingAThreadone.java and press Enter.
Now type in java CreatingAThreadone and press Enter.


C:\Java\CreatingAThreadone>javac CreatingAThreadone.java
C:\Java\CreatingAThreadone>java CreatingAThreadone
see video for results


Final thoughts

I went over quite a bit in this tutorial. You can definitely see the power of multithreading, but the downside of using that power is the issue of thread safety. In future tutorials I will demonstrate how you can overcome thread safety issues with tools such as synchronization.


Tutorials