In Java, a thread is a lightweight process that runs concurrently with other threads within a program. A program that uses threads can perform multiple tasks simultaneously, improving performance and responsiveness.
To create a thread in Java, there are two basic approaches:
Implementing the Runnable interface and passing an instance of it to a Thread constructor. Subclassing the Thread class and overriding the run() method.
Here’s an example of how to create a thread using the first approach:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
}
// create a new thread
Thread thread = new Thread(new MyRunnable());
// start the thread
thread.start();
In this example, we define a class MyRunnable that implements the Runnable interface and overrides its run() method. We then create a new Thread object and pass an instance of MyRunnable to its constructor. Finally, we start the thread by calling its start() method.
Here’s an example of how to create a thread using the second approach:
class MyThread extends Thread {
public void run() {
System.out.println("Hello from a thread!");
}
}
// create a new thread
MyThread thread = new MyThread();
// start the thread
thread.start();
In this example, we define a class MyThread that subclasses the Thread class and overrides its run() method. We then create a new instance of MyThread and start it by calling its start() method.
Both approaches are valid ways to create a thread in Java, but using the Runnable interface is generally preferred because it allows more flexibility in implementing thread behavior.
To summarize, a thread in Java is a lightweight process that runs concurrently with other threads within a program. To create a thread, you can either implement the Runnable interface and pass an instance of it to a Thread constructor, or subclass the Thread class and override its run() method. Once created, a thread can be started by calling its start() method.