Multi-Threading Basics (Thread & Runnable)
In Java, multi-threading is a crucial technology that allows multiple tasks to be performed simultaneously. By creating multiple threads of execution within a single process, tasks can be processed in parallel.
1. How to Create a Thread
There are two main ways to create a thread in Java:
- Inheriting the
Threadclass - Implementing the
Runnableinterface (Recommended)
Since Java does not support multiple inheritance, implementing the Runnable interface is more widely used, allowing the class to inherit another class if needed.
Inheriting the Thread Class
class MyThread extends Thread {
@Override
public void run() {
for(int i = 0; i < 5; i++) {
System.out.println(getName() + " is running"); // Output thread name
}
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start(); // Must call start(), not run(), to execute a new thread
t2.start();
}
}
Implementing the Runnable Interface
class MyRunnable implements Runnable {
@Override
public void run() {
for(int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " is running");
}
}
}
public class RunnableExample {
public static void main(String[] args) {
Runnable r = new MyRunnable();
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
}
Note: Calling the
run()method directly simply invokes the method within the class. You must callstart()to create and execute a new thread.
2. Daemon Threads
A daemon thread is a supplementary thread that serves to assist general threads (like the Main thread). Typical examples include the Garbage Collector (GC) or an auto-save function. When all general threads terminate, daemon threads are automatically terminated.
public class DaemonThreadExample implements Runnable {
static boolean autoSave = false;
public static void main(String[] args) {
Thread t = new Thread(new DaemonThreadExample());
t.setDaemon(true); // Must be set to daemon before calling start()
t.start();
for (int i = 1; i <= 10; i++) {
try { Thread.sleep(1000); } catch(InterruptedException e) {}
System.out.println(i);
if (i == 5) {
autoSave = true;
}
}
System.out.println("Program terminated");
}
@Override
public void run() {
while (true) {
try { Thread.sleep(3000); } catch(InterruptedException e) {}
if (autoSave) {
System.out.println("Work has been auto-saved.");
}
}
}
}
If you run this code, you will see that when the Main thread terminates after 10 seconds, the daemon thread running an infinite loop also terminates immediately.