Java Threads Basics
What is a Thread?
A thread in Java is a lightweight process that can run concurrently with other threads.
Threads share the same memory space, which allows them to communicate more easily compared to separate processes.
Note: Java provides built-in support for multithreaded programming.
Creating Threads
There are two primary ways to create threads in Java:
- Extending the Thread class
- Implementing the Runnable interface
1. Extending the Thread Class
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running.");
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // Start the thread
}
}
2. Implementing the Runnable Interface
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable is running.");
}
}
public class RunnableExample {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start(); // Start the thread
}
}
Thread Life Cycle
The life cycle of a thread can be represented in several states:
- New
- Runnable
- Blocked
- Waiting
- Timed Waiting
- Terminated
graph TD;
A[New] -->|start()| B(Runnable);
B -->|running| C[Blocked];
C -->|releases lock| B;
B -->|wait| D[Waiting];
D -->|notify| B;
B -->|sleep| E[Timed Waiting];
E --> B;
B -->|completion| F[Terminated];
Synchronization
Synchronization is necessary in multithreading to avoid data inconsistency. You can synchronize methods or blocks:
public synchronized void synchronizedMethod() {
// synchronized code
}
Tip: Use synchronized blocks whenever possible to reduce the overhead of locking.
Best Practices
- Minimize synchronization to improve performance.
- Use thread-safe collections from
java.util.concurrent
. - Avoid using
Thread.stop()
to stop a thread. - Prefer using
ExecutorService
over manually managing threads.
FAQ
What is the difference between a process and a thread?
A process is a program in execution, while a thread is a subset of a process that can run independently.
How can I stop a thread?
Use a flag to signal the thread to stop or use Thread.interrupt()
method.
What is a deadlock?
A deadlock occurs when two or more threads are blocked forever, waiting for each other to release resources.