Java provides core language support for threads. All Java programs are threaded by default even when they are not explicitly created.
The JVM itself creates a number of threads, incl. some background tasks to handle garbage collection, UI updates (JavaFX), etc.
Creating Threads
There are multiple approaches to creating threads:
- Create a new class that extends
Threadclass and overridesrun()method.class Example extends Thread { @Override public void run() { // code here } } // Run the thread new Example().start(); - Create a class that implements
Runnable. We are forced to overriderun(). This has less restrictions than extending a class since we can implement as many interfaces as we want in Java.class Example implements Runnable { @Override public void run() { // code here } } // Run the thread new Thread(new Example()).start(); - Implement
Runnableas a lambda expression.Runnable runnable = () -> { /* */ }; new Thread(runnable).start();