Middle
What is the difference between 'competition' and 'parallelism' in the context of multithreading?
sobes.tech AI
Answer from AI
Concurrency is the ability of a system to handle multiple tasks simultaneously. These tasks can be executed on a single CPU core, switching between them over time (time-sharing principle). Not necessarily means executing tasks at the exact same physical moment.
Parallelism is the actual simultaneous execution of multiple tasks at the same physical moment in time, using multiple CPU cores or multiple processors.
Main difference:
- Concurrency: Managing multiple tasks that may or may not be executed simultaneously. Focus on structuring the program to handle multiple execution threads.
- Parallelism: Physical simultaneous execution of multiple tasks. Focus on utilizing available hardware resources to speed up execution.
// Example of concurrency (without guaranteed parallel execution)
public class ConcurrentExample {
public static void main(String[] args) {
Runnable task1 = () -> System.out.println("Task 1 started on thread: " + Thread.currentThread().getName());
Runnable task2 = () -> System.out.println("Task 2 started on thread: " + Thread.currentThread().getName());
new Thread(task1).start(); // May run on the same core
new Thread(task2).start(); // May run on the same core
}
}
// Example of parallelism (requires a multi-core processor)
import java.util.List;
import java.util.Arrays;
import java.util.stream.Stream;
public class ParallelExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
numbers.parallelStream() // Uses ForkJoinPool for parallel execution
.forEach(number -> System.out.println("Processing " + number + " on thread: " + Thread.currentThread().getName()));
}
}
| Aspect | Concurrency | Parallelism |
|---|---|---|
| Goal | Managing multiple tasks | Speeding up execution |
| Requirements | Multiple tasks/threads | Multi-core processor/multiple processors |
| Execution | Alternating execution | Simultaneous execution |
| Frequency | Can be achieved on a single core | Requires multiple cores/processors |
| Example | Multitasking on a single-core system | Processing a large data array in parallel |