How do I set and get the name of a thread?

You can assign a name to thread instance by using the setName() method and get the name of the thread using the getName() method. The naming support is also available as a constructor of the Thread class such as Thread(String name) and Thread(Runnable target, String name).

package org.kodejava.lang;

public class ThreadNameDemo extends Thread {
    public ThreadNameDemo() {
    }

    public ThreadNameDemo(String name) {
        super(name);
    }

    public static void main(String[] args) {
        Thread thread1 = new ThreadNameDemo();
        thread1.setName("FOX");
        thread1.start();

        Thread thread2 = new ThreadNameDemo("DOG");
        thread2.start();
    }

    @Override
    public void run() {
        // Call getName() method to get the thread name of this
        // thread object.
        System.out.println("Running [" + this.getName() + "]");
    }
}

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

public class ThreadPriority extends Thread {
    private final String threadName;

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

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

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

How do I check if a thread is alive?

A thread is alive or running 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.lang;

public class ThreadAliveDemo implements Runnable {

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

    public void run() {
        System.out.println("Running [" +
                Thread.currentThread().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 returns true then the thread is a daemon thread, otherwise it is a user thread.

package org.kodejava.lang;

public class ThreadCheckDaemon implements Runnable {
    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());
        }
    }

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

The code snippet print the following output:

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