How do I create a multithreaded program?

Java language which was there when the language was created. This multithreading capabilities can be said like running each program on their on CPU, although the machine only has a single CPU installed.

To create a Thread program in Java we can extend the java.lang.Thread class and override the run() method. But as we know that Java class can only extend from a single class, extending Thread class makes our class cannot be inherited from another class. To solve this problem an interface was introduced, the java.lang.Runnable.

Let see the simplified demo class below. In the program below we’ll have three separated thread executions, the main thread, thread-1 and thread-2.

package org.kodejava.lang;

public class ThreadDemo extends Thread {
    public static void main(String[] args) {
        // Creates an instance of this class.
        ThreadDemo thread1 = new ThreadDemo();

        // Creates a runnable object.
        Thread thread2 = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 5; i++) {
                    sayHello();
                }
            }
        });

        // Set thread priority, the normal priority of a thread is 5.
        thread1.setPriority(4);
        thread2.setPriority(6);

        // Start the execution of thread1 and thread2
        thread1.start();
        thread2.start();

        for (int i = 0; i < 5; i++) {
            sayHello();
        }
    }

    public void run() {
        for (int i = 0; i < 5; i++) {
            sayHello();
        }
    }

    /**
     * The synchronized modifier ensure that two threads cannot execute the block
     * at the same time.
     */
    private static synchronized void sayHello() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Thread [" + Thread.currentThread().getName() +  "] ==> Hi...");
        }

        try {
            // Causes the currently executing thread to sleep for a random
            // milliseconds
            Thread.sleep((long) (Math.random() * 1000 + 1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Causes the currently executing thread object to temporarily pause
        // and allow other threads to execute.
        Thread.yield();
    }
}

How do I create a thread by implementing Runnable interface?

Here is the second way for creating a thread. We create an object that implements the java.lang.Runnable interface. For another example see How do I create a thread by extending Thread class?.

package org.kodejava.lang;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class TimeThread implements Runnable {
    private final DateFormat df = new SimpleDateFormat("hh:mm:ss");

    // The run() method will be invoked when the thread of this runnable object
    // is started.
    @Override
    public void run() {
        while (true) {
            Calendar calendar = Calendar.getInstance();
            System.out.format("Now is: %s.%n", df.format(calendar.getTime()));

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        TimeThread time = new TimeThread();

        Thread thread = new Thread(time);
        thread.start();
    }
}

An example result of this code are:

Now is: 07:18:39.
Now is: 07:18:40.
Now is: 07:18:41.
Now is: 07:18:42.
Now is: 07:18:43.

How do I create a thread by extending Thread class?

There are two ways that we can use tho create a thread. First is by extending the java.lang.Thread class and the second way is by creating a class that implements the java.lang.Runnable interface. See How do I create a thread by implementing Runnable interface?

In this example we’ll extend the Thread class. To run a code in a thread we need to provide the run() method in our class. Let’s see the code below.

package org.kodejava.lang;

public class NumberPrinter extends Thread {
    private final String threadName;
    private final int delay;

    public NumberPrinter(String threadName, int delay) {
        this.threadName = threadName;
        this.delay = delay;
    }

    // The run() method will be invoked when the thread is started.
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Thread [" + threadName + "] = " + i);

            try {
                Thread.sleep(delay);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        NumberPrinter printerA = new NumberPrinter("A", 1000);
        NumberPrinter printerB = new NumberPrinter("B", 750);

        printerA.start();
        printerB.start();
    }
}

The example result of our code is:

Thread [B] = 0
Thread [A] = 0
Thread [B] = 1
Thread [A] = 1
Thread [B] = 2
Thread [A] = 2
Thread [B] = 3
Thread [B] = 4
Thread [A] = 3
Thread [B] = 5
Thread [A] = 4
Thread [B] = 6
Thread [A] = 5
Thread [B] = 7
Thread [B] = 8
Thread [A] = 6
Thread [B] = 9
Thread [A] = 7
Thread [A] = 8
Thread [A] = 9

How do I add a delay in my program?

You have a problem that you want to add a delay for a couple of seconds in your program. Using Thread.sleep() method we can add delay in our application in a millisecond time. The Thread.sleep() need to be executed inside a try-catch block, and we need to catch the InterruptedException. Let’s see the code snippet below.

package org.kodejava.lang;

public class DelayExample {
    public static void main(String[] args) {
        // This program demonstrate how to add a delay in our 
        // application.
        for (int i = 0; i < 10; i++) {
            // Print the value of i
            System.out.println("i = " + i);

            try {
                // Using Thread.sleep() we can add delay in our 
                // application in a millisecond time. For the example 
                // below the program will take a deep breath for one 
                // second before continue to print the next value of 
                // the loop.
                Thread.sleep(1000);

                // The Thread.sleep() need to be executed inside a 
                // try-catch block and we need to catch the 
                // InterruptedException.
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            }
        }
    }
}