5 min read
Multithreading Basics
Prerequisites: Working with dates and times
A Thread runs code concurrently with the rest of the program.
Runnable describes what to run; Thread is what actually runs it.
Runnable task = () -> {
for (int i = 0; i < 3; i++) {
System.out.println("Working: " + i);
}
};
Thread thread = new Thread(task);
thread.start(); // runs concurrently
thread.join(); // wait for it to finish before continuing
Common mistakes
- Calling
thread.run()instead ofthread.start()—run()just calls the method directly on the current thread, with no new thread created at all. - Two threads modifying the same shared variable without synchronization, producing unpredictable results — the full treatment is in Concurrency in Depth, in Level 3.