Concurrency and parallelism in Java
Concurrency and parallelism are two concepts in programming that deal with executing multiple tasks, but they differ in their approaches and purposes. Here’s a breakdown of each:
Concurrency
Concurrency is about dealing with multiple tasks at once but not necessarily executing them simultaneously. It allows a system to manage multiple tasks by interleaving their execution, giving the illusion that they are running in parallel.
Key Characteristics:
- Task Interleaving: Multiple tasks make progress by being interleaved.
- Context Switching: The system switches between tasks frequently.
- Non-deterministic: The order of execution can vary.
- Resource Sharing: Tasks share resources like CPU, memory, etc.
In this example,
thread1
and thread2
run concurrently, and the output will interleave the print statements from both threads.
public class ConcurrencyExample {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println("Thread 1: " + i);
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println("Thread 2: " + i);
}
});
thread1.start();
thread2.start();
}
}
Parallelism
Parallelism is about performing multiple tasks simultaneously. It requires multiple processors or cores and is a subset of concurrency. In parallelism, tasks actually run at the same time.
Key Characteristics:
- Simultaneous Execution: Tasks run at the same time on multiple processors or cores.
- Deterministic Execution: Tasks can be executed in a predictable manner if properly managed.
- Resource Utilization: Efficient use of multiple processors or cores.
In this example, the threads are managed to run in parallel using a parallel stream in Java. This requires multiple cores to truly run in parallel.
public class ParallelismExample { public static void main(String[] args) { Runnable task1 = () -> { for (int i = 0; i < 5; i++) { System.out.println("Task 1: " + i); try { Thread.sleep(100); // Simulate some work with a small sleep } catch (InterruptedException e) { e.printStackTrace(); } } };
Runnable task2 = () -> { for (int i = 0; i < 5; i++) { System.out.println("Task 2: " + i); try { Thread.sleep(100); // Simulate some work with a small sleep } catch (InterruptedException e) { e.printStackTrace(); } } };
// Run tasks in parallel Arrays.asList(task1, task2).parallelStream().forEach(Runnable::run); }}
Comments
Post a Comment