In this post, we implement a basic Multithreading example in Java. Multithreading allows multiple threads to execute concurrently within a single program, enabling tasks to run in parallel rather than one after another. Java has built-in support for multithreading through the Thread class and the Runnable interface.
What is Multithreading?
A thread is the smallest unit of execution within a process. When a program creates multiple threads, the operating system’s thread scheduler interleaves their execution — giving each thread a slice of CPU time in turn. This makes it appear as though they are running simultaneously (and on multi-core systems, they actually can be).
In this example, we create two threads by extending the Thread class and overriding its run() method. Each thread prints a label 4 times, pausing 500 ms between prints. Both threads run concurrently, so their output interleaves.
start() — Tells the JVM to create a new OS-level thread and invoke run() on it. Calling run() directly would execute it on the current thread, not a new one.
Thread.sleep(ms) — Pauses the current thread for the given number of milliseconds, allowing other threads to execute.
InterruptedException — Must be caught when calling sleep(). It fires if another thread interrupts this one while it is sleeping.