Every application has at least one thread .
From the application programmer's point of view, you start with just one thread, called the main thread. From this thread, you can start other threads.
When a thread is created using defaultThreadFactory object, the thread will be named pool-N-thread-M where:
javase/9/docs/api/java/lang/Thread.html will return a javase/9/docs/api/java/lang/Thread.State.html
Thread State | Meaning |
---|---|
NEW | The thread has not yet started. |
RUNNABLE | The thread is executing in the Java virtual machine. |
BLOCKED | The thread is blocked waiting for a monitor lock. |
WAITING | The thread is waiting indefinitely for another thread to perform a particular action. |
TIMED_WAITING | The thread is waiting for another thread to perform an action for up to a specified waiting time. |
TERMINATED | The thread has exited. |
The thread state can also be found in a thread dump
The Thread class defines a number of methods useful for thread management. These include static methods, which provide information about, or affect the status of, the thread invoking the method.
Each thread is (associated with an instance of | represented by ) the class Thread. There are two basic strategies for using Thread objects to create a concurrent application.
An application that creates an instance of Thread must provide the code that will run in that thread.
There are two ways to do this:
The first implementation, which employs a Runnable object must be in general used because:
Example: A lambda expression of a runnable used in the argument of Thread.
new Thread(()->{
IntStream.range(0, 50).forEach(i -> {
System.out.println(i);
});
}).start();
When a statement invokes Thread.start, every statement that has a happens-before relationship with that statement also has a happens-before relationship with every statement executed by the new thread. The effects of the code that led up to the creation of the new thread are visible to the new thread.
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
When a thread terminates and causes a Thread.join in another thread to return, then all the statements executed by the terminated thread have a happens-before relationship with all the statements following the successful join.
Ie: The parent thread will wait that the child thread terminates before continuing.