Creating a Thread Part One Tutorial

In my Introduction to Multithreading Tutorial I briefly discussed that the Thread class and the Runnable interface are at the top of the multithreading hierarchy - I highly recommend watching that tutorial first. For simplistic sake, there are basically two different ways to create another thread - either extend the Thread class or implement the Runnable interface. In this tutorial I will demonstrate how to create a new thread by implementing the Runnable interface in a class that calculates if a number is prime. How do we determine if a number is prime? A number is prime if it can only be divided by itself and 1. If it can be divided by any other numbers than the number is not prime, it is composite. There are many optimizations that can be performed when calculating if a number is prime, but the only one that I will employ is that fact that a prime number cannot be even. I am going to write a terribly inefficient method (on purpose) that will basically divide the number by every odd number >= 3, by doing so we should chew up some time on a new thread.

The Runnable interface has a single abstract method named run() with a void return type. So when we implement the Runnable interface in a new custom class, we must override the run() method. The run() method is where we will put any statements or invoke any methods that will actually do something on the new thread.

To make this all work we will need to create a new object out of our class that implements Runnable. Then, in order to actually start a new thread executing, we need to create a new Thread object and invoke the constructor that takes a Runnable as a parameter. Once we have our new Thread object we can then invoke the start() method which will in turn invoke the overridden run() method from our custom class. You should be confused at this point - that is normal. Hang with me and by the end of this tutorial it should all make sense.



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.


class CreatingAThreadOne {
    public static void main(String args[]) {
        long myNum = 9223372036854775783L;

        System.out.println("Number to factor: " + myNum);
    
        MyCalculations mc = new MyCalculations(myNum);
        Thread t = new Thread(mc);
        t.start();

        Thread mainThread = Thread.currentThread(); // main thread
        int spinner = 0;
        char animation = ' ';
        System.out.println("Active threads for this thread group: " + Thread.activeCount());
        System.out.print("Calculating  ");
        while(t.isAlive()) {
            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("Active threads for this thread group: " + Thread.activeCount());
    }
}

class MyCalculations implements Runnable {
    private long numberToFactor = 0;

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

    @Override
    public void run() { // this is where the new thread starts
        isItPrime();
    }

    private void isItPrime() { // only designed to work with odd numbers
        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
                System.out.println("\n" + numberToFactor + " is NOT Prime ... first divisible by " + i);
                return;
            }
        }
        System.out.println("\n" + numberToFactor + " is Prime!");
        return;
    }
}

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
Number to factor: 9223372036854775783
Active threads for this thread group: 2
Calculating \
9223372036854775783 is Prime!
Active threads for this thread group: 1


Final thoughts

Hopefully everything somewhat makes sense after watching this tutorial, if not, try waiting a day and then watching the Introduction tutorial and then this one again. Sometimes new concepts need a while to soak in.


Tutorials