Fundamentals 9 min read

Java Thread Lifecycle and Common Thread APIs

This article explains Java's thread lifecycle, detailing its six states—New, Runnable, Blocked, Waiting, Timed_waiting, and Terminated—and describes eleven commonly used thread APIs such as join(), wait(), notify(), yield(), sleep(), currentThread(), getName(), getId(), getPriority(), setPriority() and stop().

Full-Stack Internet Architecture
Full-Stack Internet Architecture
Full-Stack Internet Architecture
Java Thread Lifecycle and Common Thread APIs

The article introduces the second part of the "One-Stop Multithreading" series, focusing on the lifecycle of Java threads and the most frequently used thread APIs.

According to the source code of java.lang.Thread, a thread can be in one of six states: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, and TERMINATED.

public enum State {<br/>  NEW,<br/>  RUNNABLE,<br/>  BLOCKED,<br/>  WAITING,<br/>  TIMED_WAITING,<br/>  TERMINATED;<br/>}

1. New – The thread has been created but not started yet. MyThread myThread = new MyThread(); 2. Runnable – After calling start(), the thread is ready to run and waits for CPU scheduling. myThread.start(); 3. Blocked – The thread is waiting to acquire a monitor lock (e.g., entering a synchronized block).

4. Waiting – The thread is waiting indefinitely for another thread to perform an action, typically after invoking Object.wait(), Thread.join(), or LockSupport.park().

5. Timed_waiting – Similar to Waiting but with a timeout, caused by methods such as Thread.sleep(), Object.wait(long), Thread.join(long), LockSupport.parkNanos, or LockSupport.parkUntil.

6. Terminated – The thread has completed execution, been stopped, or terminated due to an uncaught exception.

Common Thread APIs

1. join()

join()

blocks the calling thread until the target thread finishes.

public class MyRunnable implements Runnable {<br/>    @Override<br/>    public void run() {<br/>        for (int i = 0; i < 100; i++) {<br/>            System.out.println("小齐666:" + i);<br/>        }<br/>    }<br/><br/>    public static void main(String[] args) throws InterruptedException {<br/>        Thread t = new Thread(new MyRunnable());<br/>        t.start();<br/>        t.join();<br/>        for (int i = 0; i < 100; i++) {<br/>            System.out.println("主线程" + i + ":齐姐666");<br/>        }<br/>    }<br/>}

2. wait() and notify()

wait()

is defined in Object and causes the current thread to wait until another thread calls notify() or notifyAll(). A timed version can be used to wake up after a specified period.

3. yield()

yield()

hints to the scheduler that the current thread is willing to pause and let other threads run.

4. sleep()

sleep(long millis)

pauses the current thread for the given time and throws InterruptedException, which must be caught.

myThread.sleep(1000); // sleep 1 second

5. currentThread()

Returns a reference to the currently executing Thread object.

System.out.println(Thread.currentThread());

6. getName()

Retrieves the thread’s name; it can be set at creation.

Thread t = new Thread(new MyRunnable(), "壹齐学");

7. getId()

Returns the unique identifier of the thread.

8. getPriority() / setPriority()

Threads have a priority between 1 and 10; higher priority increases the chance of earlier execution. Setting a value outside this range throws IllegalArgumentException.

public final static int MIN_PRIORITY = 1;<br/>public final static int NORM_PRIORITY = 5;<br/>public final static int MAX_PRIORITY = 10;

9. stop()

The stop() method forcibly terminates a thread but is deprecated because it can leave shared data in an inconsistent state.

Overall, the article provides a clear overview of thread states and the essential APIs developers need to manage multithreaded Java applications effectively.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaconcurrencyprogrammingThreadmultithreadingAPI
Full-Stack Internet Architecture
Written by

Full-Stack Internet Architecture

Introducing full-stack Internet architecture technologies centered on Java

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.