JavaMultithreading

Threads as objects

Threads in Java

Java was originally designed with built-in multithreading support. Threads are supported here at the level of JVM and at the level of language by special keywords and at the level of the standard library. Every Java program has at least one thread called main created automatically by the JVM to execute statements inside the main method. But actually, there are also other default threads in a Java program exist (e.g., a separated thread for the garbage collector).

Throughout all stages of development of the Java language, the approach for multithreading was changed from the low-level threads to using some high-level abstractions. However, understanding the fundamental base remains very important to be a good developer.

A class for threads

Each thread is represented by an object that is an instance of the java.lang.Thread class (or its subclass). This class has a static method named currentThread to obtain a reference to the currently executing thread object:

Thread thread = Thread.currentThread(); // the current thread

Any thread has a name, an identifier (long), a priority, and some other characteristics which can be obtained through its methods.

The information about the main thread

The example below demonstrates the characteristics obtaining a reference to the main thread through an object of the Thread class.

public class MainThreadDemo {
    public static void main(String[] args) {
        Thread t = Thread.currentThread(); // main thread

        System.out.println("Name: " + t.getName());
        System.out.println("ID: " + t.getId());
        System.out.println("Alive: " + t.isAlive());
        System.out.println("Priority: " + t.getPriority());
        System.out.println("Daemon: " + t.isDaemon());

        t.setName("my-thread");
        System.out.println("New name: " + t.getName());
    }
}

All statements in this program are executed by the main thread.

The invocation t.isAlive() returns whether the thread has been started and not died yet. Every thread has a priority, and thread with a higher priority are executed in preference to threads with lower priorities. The invocation t.isDaemon() checks whether the thread is a daemon (comes from UNIX terminology). A daemon thread is a low priority thread that runs in the background to perform tasks such as garbage collection and so on. JVM does not wait for daemon threads before exiting while it waits for non-daemon threads.

After starting this program, you will see results like below.

Name: main
ID: 1
Alive: true
Priority: 5
Daemon: false
New name: my-thread

The same code can work for any current thread, not just main.

2 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo