Difference between Thread and Process

Difference between Thread and Process

Process

A process is an independent program in execution, having its own memory space. Multiple processes can run simultaneously on the operating system, and each process has its own address space. Processes do not share memory directly and require inter-process communication mechanisms to exchange data.

Thread

A thread is a smaller unit of a process, also known as a lightweight process. Multiple threads can exist within the same process and share the same memory space. Threads within the same process can communicate directly since they share the same memory.

Thread and Process

Key Differences Thread and Process

1. Memory Sharing

  •  Process: Each process has its own memory space.
  •  Thread: Threads share the same memory space within the process.

2. Resource Allocation

  • Process: More resource-intensive as each process requires its own memory and resources.
  • Thread: Less resource-intensive since threads share resources within a process.

3. Inter-process Communication

  • Process: Requires complex communication mechanisms (e.g., pipes, sockets).
  • Thread: Can communicate directly through shared memory.

4. Creation Time

  • Process: Longer creation time due to resource allocation.
  • Thread: Faster creation time as it uses existing process resources.

5. Context Switching

  • Process: Slower due to the need to switch memory spaces.
  • Thread: Faster as it switches within the same memory space.

Example
java
import java.io.IOException;

public class ProcessExample {
    public static void main(String[] args) {
        try {
            // Running a process
            Process process = Runtime.getRuntime().exec("notepad.exe");
            
            // Waiting for the process to terminate
            process.waitFor();
            
            System.out.println("Process exited with code: " + process.exitValue());
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Creating and Running a Thread

java
class MyThread extends Thread {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("Thread ID: " + Thread.currentThread().getId() + " Value: " + i);
            try {
                Thread.sleep(500); // Sleep for 500 milliseconds
            } catch (InterruptedException e) {
                System.out.println(e);
            }	
        }
    }
}

public class ThreadExample {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        t1.start();
    }
}

Homepage

Readmore