Imagine trying to download something, and your mouse freezes, preventing you from doing anything else. Why does this happen? In today's computers, it's because the operating system is running multiple processes simultaneously.
A running program, meaning a program that the user has written, is allocated memory space and executed by the operating system. This process consists of resources such as data, memory, and threads.
A thread is the entity that actually performs the work within a process. Every process has at least one thread. If a process has only one thread, it's called single-threaded; if it has more than one thread, it's called multi-threaded.
Java allows only single inheritance, making this method less commonly used.
class ThreadWithClass extends Thread {
public void run() // Override the run() method of the Thread class
// Work to be done in the thread
}
ThreadWithClass thread1 = new ThreadWithClass(); // Create a thread
thread1.start(); // Start the thread
class ThreadWithClass extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(getName()); // Returns the name of the currently executing thread.
}
}
}
As Java supports multiple interfaces, this method provides more flexibility.
class ThreadWithRunnable implements Runnable {
public void run() // Implement the run() method of the Runnable interface
// Define the work to be done in the thread
}
Thread thread2 = new Thread(new ThreadWithRunnable());
thread2.start(); // Start the thread
class ThreadWithRunnable implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()); // Returns the name of the currently executing thread.
}
}
}