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.lang;

public class DaemonThread implements Runnable {
    private final String threadName;

    private DaemonThread(String threadName) {
        this.threadName = 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();
    }

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

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.lang;

import java.util.Calendar;

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

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

    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();
    }

    // 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 + "]");
    }
}

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

Start thread [FirstThread]
Start thread [SecondThread]
[FirstThread]Mon Oct 25 11:52:13 CST 2021
[FirstThread]Mon Oct 25 11:52:14 CST 2021
[SecondThread]Mon Oct 25 11:52:15 CST 2021
[FirstThread]Mon Oct 25 11:52:15 CST 2021
[FirstThread]Mon Oct 25 11:52:16 CST 2021

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.lang;

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

    // 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...");
    }
}

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.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.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.lang.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);
    }
}