Java Multithreading: Concepts, Creation Methods, Lifecycle, and Termination Techniques
This article offers a thorough tutorial on Java multithreading, explaining processes versus threads, thread creation approaches, lifecycle states, priority handling, and various safe and unsafe ways to stop threads, complete with practical code examples and best‑practice warnings.
This article provides a comprehensive guide to Java multithreading, covering fundamental concepts such as the difference between processes and threads, the definition of multithreading, and why it is essential for building high‑concurrency systems.
It discusses the advantages (improved performance, better CPU utilization) and disadvantages (reduced readability, higher memory usage, thread‑safety concerns) of using multiple threads, and introduces key concepts like synchronization, asynchronous execution, concurrency vs. parallelism, high‑concurrency metrics, critical sections, and blocking vs. non‑blocking states.
Three primary ways to create threads are presented: extending Thread, implementing Runnable, and using a thread pool via Executors.newFixedThreadPool. Sample code snippets illustrate each method.
public class MyThread extends Thread {
@Override
public void run() {
super.run();
System.out.println("MyThread");
}
} public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("MyRunnable");
}
} public class ThreadPool {
private static int POOL_NUM = 10;
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < POOL_NUM; i++) {
RunnableThread thread = new RunnableThread();
executorService.execute(thread);
}
}
}
class RunnableThread implements Runnable {
private int THREAD_NUM = 10;
public void run() {
for (int i = 0; i < THREAD_NUM; i++) {
System.out.println("线程" + Thread.currentThread() + " " + i);
}
}
}The thread lifecycle is described with the states NEW, RUNNABLE, RUNNING, BLOCKED, WAITING, TIMED_WAITING, and TERMINATED, along with explanations of natural and abnormal termination.
Thread priority levels (MIN_PRIORITY, NORM_PRIORITY, MAX_PRIORITY) and their inheritance behavior are explained.
Various thread‑termination techniques are examined, including graceful interruption with interrupt(), handling InterruptedException in sleep(), using exceptions to break loops, the deprecated stop() method and its associated ThreadDeath exception, and returning from the run() method after detecting interruption.
public class MyThread extends Thread {
public void run() {
super.run();
for (int i = 0; i < 500000; i++) {
System.out.println("i=" + (i + 1));
}
}
}
public class Run {
public static void main(String[] args) {
Thread thread = new MyThread();
thread.start();
try {
Thread.sleep(2000);
thread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}Potential pitfalls of using stop(), such as lock release leading to data inconsistency, are highlighted with example code.
public class MyThread extends Thread {
private int i = 0;
public void run() {
super.run();
try {
while (true) {
System.out.println("i=" + i);
i++;
Thread.sleep(200);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Run {
public static void main(String[] args) throws InterruptedException {
Thread thread = new MyThread();
thread.start();
Thread.sleep(2000);
thread.stop();
}
}A synchronized‑object example demonstrates how abruptly stopping a thread can leave shared data in an inconsistent state.
public class SynchronizedObject {
private String name = "a";
private String password = "aa";
public synchronized void printString(String name, String password) {
try {
this.name = name;
Thread.sleep(100000);
this.password = password;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// getters and setters omitted for brevity
}
public class MyThread extends Thread {
private SynchronizedObject synchronizedObject;
public MyThread(SynchronizedObject synchronizedObject) {
this.synchronizedObject = synchronizedObject;
}
public void run() {
synchronizedObject.printString("b", "bb");
}
}
public class Run {
public static void main(String[] args) throws InterruptedException {
SynchronizedObject synchronizedObject = new SynchronizedObject();
Thread thread = new MyThread(synchronizedObject);
thread.start();
Thread.sleep(500);
thread.stop();
System.out.println(synchronizedObject.getName() + " " + synchronizedObject.getPassword());
}
}Finally, the article lists reference books and online articles for further reading on Java concurrency.
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.
Big Data Technology & Architecture
Wang Zhiwu, a big data expert, dedicated to sharing big data technology.
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.
