Multithreading in Java allows multiple parts of a program to run concurrently. A thread is a lightweight sub-process that improves application performance and responsiveness.
Java provides two primary ways to create threads:
// Creating a thread by extending Thread class
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
// Creating a thread using Runnable interface
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable thread is running");
}
public static void main(String[] args) {
MyRunnable r1 = new MyRunnable();
Thread t1 = new Thread(r1);
t1.start();
}
Both examples create a new thread and execute the run() method concurrently with the main thread. The start() method internally calls run().
In Java, when you start two threads, you cannot guarantee which one finishes first. The Thread Scheduler decides execution time. Click "Start" below to simulate two threads racing concurrently.
run() directlyThread.sleep() to observe execution ordersetName()