Sobes.tech
Junior

What is a process and a thread? What are their differences?

sobes.tech AI

Answer from AI

A process is a running program with its own address space, resources (file descriptors, network connections), and execution context.

A thread (execution thread, thread) is the smallest unit of execution within a process. A process can contain one or more threads, which share its resources but have their own call stack, execution context, and instruction counter.

Main differences:

Characteristic Process Thread
Isolation Complete. One process does not affect another. Partial. Threads share process resources.
Data exchange Via IPC (inter-process communication). Lightweight. Through shared variables within the process.
Context switch Costly. Requires saving and restoring the entire process state. Cheaper. Requires saving and restoring thread state.
Creation Costly. Requires resource allocation. Cheaper. Requires stack allocation.
Termination Terminating a process ends all its threads. Terminating a thread does not affect other threads or the process.

Example of creating a process (external command) in Java:

// Java
Process process = Runtime.getRuntime().exec("ls -l");
// Further work with the process: input/output handling, etc.

Example of creating a thread in Java:

// Java
Runnable task = () -> {
    System.out.println("Hello from thread: " + Thread.currentThread().getName());
};

Thread thread = new Thread(task);
thread.start(); // Starting the thread