java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to create a multithread program?

A thread is a unit of program execution that runs on their own thread. Multithreading is a core capabilities of the 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 extends the java.lang.Thread class and override the run() method. But as we know that Java class can only extends 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 com.javacoderanch.example.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 < 1000; 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();
    }
}