Multithreading lets a Java program do several tasks at the same time, such as handling many user requests. Interviewers ask about it because mistakes cause bugs that are hard to find.
Threads
A thread is a separate path of execution inside a program. You can create one by implementing Runnable, or, more commonly today, by submitting tasks to an ExecutorService.
The main risk: shared data
When two threads change the same data at once, results can be wrong. This is called a race condition.
Ways to stay safe
- Use synchronized blocks or locks around shared changes.
- Prefer thread-safe classes, such as ConcurrentHashMap.
- Avoid sharing changeable data where you can.
Interview questions to prepare
- What is the difference between a process and a thread?
- What is a deadlock, and how can you avoid one?
- Why use an ExecutorService instead of creating threads by hand?
Next step: see our Java Full Stack course at ScholarLogic, or book a free demo class. A counsellor will share the fee and the next batch dates.
