Multitasking: Multiprocessing vs Multithreading
Multitasking is the ability of a computer to run several tasks at the same time, such as playing music while you type a document. There are two ways to multitask. Process-based multitasking (multiprocessing) runs several separate programs at once. Thread-based multitasking (multithreading) runs several tasks inside one program. Java programs mainly use multithreading. In this lesson, you will learn the differences, and the related ideas of concurrency and parallelism.
Process-Based vs Thread-Based Multitasking
| Multiprocessing | Multithreading | |
|---|---|---|
| Unit of work | A process (program) | A thread inside a process |
| Memory | Each process has its own | Threads share their process's heap |
| Switching cost | High | Low |
| Communication | Slow (pipes, sockets, files) | Fast (shared objects) |
| Isolation | Strong: one crash rarely affects others | Weak: shared data can be corrupted |
| Example | Browser, editor and music player running together | A web server handling many requests in one JVM |
Concurrency vs Parallelism
- Concurrency means several tasks are in progress at the same time. On one CPU core, the system switches between them quickly, so they take turns.
- Parallelism means several tasks run at the same instant on different CPU cores.
Java threads give you concurrency on any machine, and parallelism when the computer has more than one core.
Example: How Many Cores?
Let's see an example that asks the JVM how many processors it can use. The number depends on the computer, so the output is a sample.
public class Cores {
public static void main(String[] args) {
int cores = Runtime.getRuntime().availableProcessors();
System.out.println("Available processors: " + cores);
System.out.println("Current thread: "
+ Thread.currentThread().getName());
System.out.println("Live threads in this JVM: "
+ (Thread.activeCount() >= 1));
}
}Available processors: 10
Current thread: main
Live threads in this JVM: trueExplanation: availableProcessors() tells you how many threads can truly run in parallel. Every program runs in at least one thread, main. The JVM also runs its own background threads, such as the garbage collector.
Common Mistakes
Thinking more threads always means faster. Beyond the number of cores, CPU-heavy threads just take turns.
Confusing concurrency with parallelism. Concurrency is about structure; parallelism needs multiple cores.
Practice
- Easy: Print the number of available processors and explain what it means for a program that sorts big arrays.
- Harder: Start as many threads as there are processors, each printing its name once, and join them all.
Key Takeaways
Was this tutorial helpful?