How do I use join method to wait for threads to finish?

If you want a thread to work until another thread dies, you can join the thread onto the end of the another thread using the join() method. For example, you want thread B only work until thread A completes its work, then you want thread B to join thread A.

package org.kodejava.example.lang;

public class ThreadJoin implements Runnable {
    private int numberOfLoop;

    private ThreadJoin(int numberOfLoop) {
        this.numberOfLoop = numberOfLoop;
    }

    public void run() {
        System.out.println("[" +
            Thread.currentThread().getName() + "] - Running.");

        for (int i = 0; i < this.numberOfLoop; i++) {
            System.out.println("[" +
                Thread.currentThread().getName() + "] " + i);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("[" +
            Thread.currentThread().getName() + "] - Done.");
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new ThreadJoin(10), "FirstThread");
        Thread t2 = new Thread(new ThreadJoin(20), "SecondThread");

        try {
            // start t1 and waits for this thread to die before
            // starting the t2 thread.
            t1.start();
            t1.join();

            // start t2
            t2.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

How do I set the priority of a thread?

Threads always run with some priority, usually represented as a number between 1 and 10 (although in some cases the range is less than 10). A thread gets a default priority that is the priority of the thread of execution that creates it.

But, you can also set a thread’s priority directly by calling the setPriority() method on a Thread instance. One thing to remember about thread priorities is never rely on thread priorities, because thread-scheduling priority behavior is not guaranteed.

package org.kodejava.example.lang;

public class ThreadPriority extends Thread {
    private String threadName;

    ThreadPriority(String threadName) {
        this.threadName = threadName;
    }

    @Override
    public void run() {
        System.out.println("Running [" + threadName + "]");
        for (int i = 1; i <= 10; i++) {
            System.out.println("[" + threadName + "] => " + i);

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

    public static void main(String[] args) {
        ThreadPriority thread1 = new ThreadPriority("First");
        ThreadPriority thread2 = new ThreadPriority("Second");
        ThreadPriority thread3 = new ThreadPriority("Third");
        ThreadPriority thread4 = new ThreadPriority("Fourth");
        ThreadPriority thread5 = new ThreadPriority("Fifth");

        // set thread1 to minimum priority = 1
        thread1.setPriority(Thread.MIN_PRIORITY);

        // set thread2 to priority 2
        thread2.setPriority(2);

        // set thread3 to normal priority = 5
        thread3.setPriority(Thread.NORM_PRIORITY);

        // set thread4 to priority 8
        thread4.setPriority(8);

        // set thread5 to maximum priority = 10
        thread5.setPriority(Thread.MAX_PRIORITY);

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
    }
}

How do I check if a thread is alive?

A thread is alive or runningn if it has been started and has not yet died. To check whether a thread is alive use the isAlive() method of Thread class. It will return true if this thread is alive, otherwise return false.

package org.kodejava.example.lang;

public class ThreadAliveDemo implements Runnable {

    public void run() {
        System.out.println("Running [" +
            Thread.currentThread().getName() + "].");
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new ThreadAliveDemo(), "FirstThread");
        Thread t2 = new Thread(new ThreadAliveDemo(), "SecondThread");

        // start the t1
        t1.start();

        // Check to see if the first thread is alive or not.
        if (t1.isAlive()) {
            System.out.format("%s is alive.%n", t1.getName());
        } else {
            System.out.format("%s is not alive.%n", t1.getName());
        }

        // Check to see if the second thread is alive or not.
        // It should be return false because t2 hasn't been started.
        if (t2.isAlive()) {
            System.out.format("%s is alive.%n", t2.getName());
        } else {
            System.out.format("%s is not alive.%n", t2.getName());
        }
    }
}

How do I check if a thread is a daemon thread?

You can test if a thread is a daemon thread or a user thread by calling the isDaemon() method of the Thread class. If it return true then the thread is a daemon thread, otherwise it is a user thread.

package org.kodejava.example.lang;

public class ThreadCheckDaemon implements Runnable {
    public void run() {
        System.out.println("Running [" +
            Thread.currentThread().getName() + "]");
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new ThreadCheckDaemon(), "FirstThread");
        Thread t2 = new Thread(new ThreadCheckDaemon(), "SecondThread");

        t1.setDaemon(true);
        t1.start();
        t2.start();

        if (t1.isDaemon()) {
            System.out.format("%s is a daemon thread.%n", t1.getName());
        } else {
            System.out.format("%s is a user thread.%n", t1.getName());
        }

        if (t2.isDaemon()) {
            System.out.format("%s is a daemon thread %n", t2.getName());
        } else {
            System.out.format("%s is a user thread %n", t2.getName());
        }
    }
}

The code snippet print the following output:

Running [SecondThread]
Running [FirstThread]
FirstThread is a daemon thread.
SecondThread is a user thread 

How do I create a daemon thread?

A daemon thread is simply a background thread that is subordinate to the thread that creates it, so when the thread that created the daemon thread ends, the daemon thread dies with it. A thread that is not a daemon thread is called a user thread. To create a daemon thread, call setDaemon() method with a true boolean value as argument before the thread is started.

package org.kodejava.example.lang;

public class DaemonThread implements Runnable {
    private String threadName;

    private DaemonThread(String threadName) {
        this.threadName = threadName;
    }

    public void run() {
        System.out.println("Running [" + threadName + "]");
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new DaemonThread("FirstThread"));
        Thread t2 = new Thread(new DaemonThread("SecondThread"));

        // t1 is as daemon thread
        t1.setDaemon(true);
        t1.start();

        // t2 is a user thread
        t2.start();
    }
}

How do I use the sleep method of the Thread class?

Here is another example that use the Thread.sleep() method. In the example we create two instances of the ThreadSleepAnotherDemo, we give each thread a name and the sleep interval so that we can see how to thread execution.

package org.kodejava.example.lang;

import java.util.Calendar;

public class ThreadSleep implements Runnable {
    private String threadName;
    private long sleep;

    public ThreadSleep(String threadName, long sleep) {
        this.threadName = threadName;
        this.sleep = sleep;
    }

    // The run() method will be invoked when the thread is started.
    public void run() {
        System.out.println("Start thread [" + this.threadName + "]");
        try {
            while (true) {
                // Pause the thread for "sleep" milliseconds.
                Thread.sleep(this.sleep);
                System.out.println("[" + threadName + "]" +
                    Calendar.getInstance().getTime());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Finish thread [" + this.threadName + "]");
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(new ThreadSleep("FirstThread", 1000));
        Thread thread2 = new Thread(new ThreadSleep("SecondThread", 3000));

        // Start the threads
        thread1.start();
        thread2.start();
    }
}

These are the sample output produced by the code snippet above:

Start thread [FirstThread]
Start thread [SecondThread]
[FirstThread]Sun Aug 13 10:42:53 WITA 2017
[FirstThread]Sun Aug 13 10:42:54 WITA 2017
[SecondThread]Sun Aug 13 10:42:55 WITA 2017
[FirstThread]Sun Aug 13 10:42:55 WITA 2017
[FirstThread]Sun Aug 13 10:42:56 WITA 2017

How do I pause the current thread?

You can pause a current thread for a number of milliseconds by using the sleep() method of the Thread class. While the current thread is sleeping, it will allow other threads to execute.

package org.kodejava.example.lang;

public class ThreadSleepDemo implements Runnable {
    // The run() method will be invoked when the thread is started.
    public void run() {
        System.out.println("Start..");
        try {
            // Wait for 10 seconds
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Finish...");
    }

    public static void main(String[] args) {
        Thread thread = new Thread(new ThreadSleepDemo());
        thread.start();
    }
}

How do I start a thread execution?

To make a thread begin its execution, call the start() method on a Thread or Runnable instance. Then the Java Virtual Machine will calls the run method of this thread.

The snippet below is showing how to create a thread by implementing the Runnable interface.

package org.kodejava.example.lang;

public class ThreadRun implements Runnable {

    public static void main(String[] args) {
        // Instantiate ThreadRun
        ThreadRun runner = new ThreadRun();

        // Create instance of Thread and passing ThreadRun object
        // as argument.
        Thread thread = new Thread(runner);

        // By passing Runnable object, it tells the
        // thread to use run() of Runnable object.
        thread.start();
    }

    public void run() {
        System.out.println("Running..");
    }
}

The snippet below is showing how to create a thread by extending the Thread class.

package org.kodejava.example.lang;

public class ThreadStart extends Thread {

    public static void main(String[] args) {
        ThreadStart thread = new ThreadStart();

        // Start this thread
        thread.start();
    }

    /**
     * The run() method will be invoked when the thread is started.
     */
    @Override
    public void run() {
        System.out.println("Running..");
    }
}

How do I get current number of live threads?

package org.kodejava.example.management;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

public class ThreadCount {

    public static void main(String[] args) {
        // Get the managed bean for the thread system of the Java
        // virtual machine.
        ThreadMXBean bean = ManagementFactory.getThreadMXBean();

        // Get the current number of live threads including both
        // daemon and non-daemon threads.
        int threadCount = bean.getThreadCount();
        System.out.println("Thread Count = " + threadCount);
    }
}

How do I get the name of current executed method?

package org.kodejava.example.lang;

public class GetCurrentMethodName {
    public static void main(String[] args) {
        // Get the current executing method name
        String methodName =
            Thread.currentThread().getStackTrace()[1].getMethodName();
        System.out.println("methodName = " + methodName);

        GetCurrentMethodName obj = new GetCurrentMethodName();
        obj.executeAMethod();
    }

    private void executeAMethod() {
        // Get the current executing method name
        String methodName =
            Thread.currentThread().getStackTrace()[1].getMethodName();
        System.out.println("methodName = " + methodName);
    }
}

This program will print out the following string:

methodName = main
methodName = executeAMethod