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
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 threadlong), a priority, and some other characteristics which can be obtained through its methods.The information about the main thread
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());
}
}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.Name: main
ID: 1
Alive: true
Priority: 5
Daemon: false
New name: my-threadThe same code can work for any current thread, not just main.