Sobes.tech
Middle

Mis vahe on 'konkurentslikul' ja 'paralleelil' mitme lõime kontekstis?

sobes.tech AI

Vastus AI-lt

Concurrency is the system's ability to process multiple tasks simultaneously. These tasks can be executed on a single processor core, switching between them over time (time-sharing principle). Not necessarily means executing tasks at the same physical moment.

Parallelism is the real simultaneous execution of multiple tasks at the same physical moment, using multiple processor cores or multiple processors.

Main difference:

  • Concurrency: Managing several tasks, which may or may not be executed simultaneously. Focus on structuring the program for multi-threaded processing.
  • Parallelism: Physical simultaneous execution of multiple tasks. Focus on utilizing available hardware resources to speed up execution.
// Example of concurrency (without guarantee of 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 multi-core processor)
import java.util.List;
import java.util.Arrays;

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 Accelerating 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 Parallel processing of large data array