Category: java
Understanding Processes and Threads
Published on 27 Oct 2026
Explanation
A process is a program in execution with its own address space and resources. A thread is an execution path within a process. Threads in the same process share heap objects but have separate stacks.
Code:
public class ProcessThreadDemo {
public static void main(String[] args) {
Thread worker = new Thread(() ->
System.out.println("Worker: " + Thread.currentThread().getName()));
worker.start();
System.out.println("Main: " + Thread.currentThread().getName());
}
}
Explanation
Separate processes generally have isolated memory. Threads in one Java process can access the same objects, which makes sharing convenient but requires thread-safety when data is modified concurrently.
Code:
class SharedData { int value = 10; }
public class SharedMemoryDemo {
public static void main(String[] args) throws InterruptedException {
SharedData data = new SharedData();
Thread t = new Thread(() -> data.value = 20);
t.start();
t.join();
System.out.println(data.value);
}
}
Explanation
Creating a process usually involves more overhead than creating a thread. Threads are useful for concurrent work inside an application, but creating too many platform threads can still consume significant memory and operating-system resources.
Code:
public class MultipleThreadsDemo {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
int taskId = i;
new Thread(() -> System.out.println("Task " + taskId)).start();
}
}
}
Explanation
Processes often communicate through sockets, pipes, or other inter-process communication mechanisms. Threads can communicate through shared Java objects, but shared mutable state must be coordinated safely.
Code:
class Message { String text = "Hello"; }
public class ThreadCommunicationDemo {
public static void main(String[] args) throws InterruptedException {
Message message = new Message();
Thread t = new Thread(() -> System.out.println(message.text));
t.start();
t.join();
}
}
Explanation
Use processes when strong isolation is important. Use threads when tasks need to run concurrently within the same application, such as handling requests or processing background work. Executors are usually preferable to manually creating many threads.
Code:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExecutorDemo {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.submit(() -> System.out.println("Handle request A"));
pool.submit(() -> System.out.println("Handle request B"));
pool.shutdown();
}
}