Mastering Java Threads: From Basics to Priority and State Management
This article explains the fundamentals of Java threads, contrasting them with processes, demonstrates thread creation via extending Thread and implementing Runnable, discusses the benefits of multithreading, covers thread priority settings, and details the lifecycle states and transitions with practical code examples.
What Is a Thread?
Before learning about threads, it is essential to understand processes and their differences. A process is the smallest unit of resource allocation, while a thread is the smallest unit the operating system schedules. Processes are independent, making data sharing difficult and context switches costly. A process can contain multiple threads that share data, each with its own counter, stack, and local variables.
Creating Threads in Java
There are four common ways to create threads in Java: extending the Thread class, implementing the Runnable interface, using Callable with Future, and employing a thread pool. This article focuses on the first two methods.
Extending Thread
Thread thread = new Thread(){
@Override
public void run() {
// task to execute
}
};
thread.start();Implementing Runnable
// Custom Runnable
class MyRunnable implements Runnable {
@Override
public void run() {
// task to execute
}
}
// Create and start thread
Runnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();Why Use Multithreading?
Multithreading allows different functions of an application to run concurrently, improving resource utilization on multi‑core CPUs and enhancing responsiveness—for example, playing music while chatting or loading data in the background.
Better resource utilization Multiple threads can run on multiple cores, reducing overall execution time.
Faster response time Time‑consuming tasks can be offloaded to background threads, keeping the UI responsive.
Thread Priority
In Java, thread priority is an integer from 1 (lowest) to 10 (highest), with the default being 5. Higher‑priority threads are more likely to be scheduled before lower‑priority ones.
public class ThreadPriority {
public static void main(String[] args) {
ThreadA A = new ThreadA();
ThreadB B = new ThreadB();
ThreadC C = new ThreadC();
A.setPriority(1);
B.setPriority(10);
System.out.println(A.getPriority());
System.out.println(B.getPriority());
System.out.println(C.getPriority());
A.start();
B.start();
C.start();
}
}
class ThreadA extends Thread {
@Override
public void run() { System.out.println("A thread"); }
}
class ThreadB extends Thread {
@Override
public void run() { System.out.println("B thread"); }
}
class ThreadC extends Thread {
@Override
public void run() { System.out.println("C thread"); }
}Thread Lifecycle States
Java threads have six states: New (created, not started), Runnable (ready or running), Blocked (waiting for a lock), Waiting (awaiting notification), Timed Waiting (waiting with timeout), and Terminated (finished or cancelled). State transitions occur via methods such as start(), wait(), notify(), sleep(), and lock acquisition.
Example transition: New → Runnable (call start() ), Runnable → Waiting (call wait() ), Waiting → Runnable (call notify() ), Runnable → Blocked (failed to acquire lock), Blocked → Runnable (lock acquired), Runnable → Terminated (run method completes).
Waiting vs. Timed Waiting
Both states use similar methods, but timed waiting adds a timeout, ensuring the thread returns to runnable after a specified period even without notification.
synchronized (obj) {
while (!condition) {
obj.wait(); // waits indefinitely
}
// continue processing
}Reference
[1] 方腾飞. Java Concurrency Programming Art .
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
