Threading Basics
Multithreading allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a Thread.
Creating a Thread
There are two main ways to create a thread in Java:
1. Extend Thread Class
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}
// Start it:
MyThread t = new MyThread();
t.start();
2. Implement Runnable Interface (Preferred)
Better because you can still extend another class.
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread running");
}
}
// Start it:
Thread t = new Thread(new MyRunnable());
t.start();
Thread Lifecycle
A thread goes through various states: New, Runnable, Running, Blocked/Waiting, Terminated.
Full Example
Output
Click Run to execute your code
Summary
- Use
start()to execute therun()method in a separate thread. - Directly calling
run()does not start a new thread. - Runnable is generally preferred over extending Thread.
Enjoying these tutorials?