Java.Multithreading.What is the difference between a process and a thread?

🧠 What’s the Difference Between a Process and a Thread?

FeatureProcessThread
DefinitionA program in execution (independent)A lightweight unit of execution within a process
MemoryHas its own memory spaceShares memory with other threads in same process
IsolationFully isolated from othersNot isolated — shares heap & static data
CommunicationExpensive (IPC: sockets, pipes)Cheap (shared memory, synchronized access)
OverheadHeavyLight
Crash impactCrash of one process doesn’t affect othersCrash of one thread can affect whole process
SchedulingHandled by OSAlso scheduled by OS (as lightweight processes)

🔧 Real World Analogy

  • A process is like a house — it has its own walls, kitchen, bathroom.
  • A thread is like a person inside the house — multiple people (threads) can do things in parallel but share the same fridge, bathroom, etc.

📦 Java-Specific View

When you run a Java app:

java MyApp
  • JVM creates 1 process: the Java process.
  • You can create many threads using:
    • new Thread()
    • ExecutorService
    • ForkJoinPool, etc.

All threads share the same heap (objects, static fields), but have their own call stacks (method frames, local variables).

🧪 Code Example

public class Demo {
    public static void main(String[] args) {
        new Thread(() -> System.out.println("Hello from thread")).start();
        System.out.println("Hello from main thread");
    }
}

Here:

  • Both threads share the same process and memory
  • They can access the same objects, but must synchronize to avoid conflicts

🔥 Summary

TopicThreadProcess
Memory Sharing✅ Shares with others in process❌ Separate memory
Communication Cost🟢 Low (shared mem)🔴 High (IPC)
Overhead🟢 Low🔴 High
Failure Isolation❌ Shared fate✅ Isolated
Use in JavaBuilt-in (Thread, Executors)Managed via ProcessBuilder
This entry was posted in Без рубрики. Bookmark the permalink.