Creating a thread in Java involves several steps:
Define the code to be executed in the thread.
The first step in creating a thread is to define the code that will be executed when the thread runs. This can be done by extending the Thread class or implementing the Runnable interface.
Create an instance of the Thread class.
Once the code to be executed in the thread has been defined, the next step is to create an instance of the Thread class. This can be done by calling the Thread constructor.
Start the thread.
After creating the Thread instance, the thread can be started by calling the start() method. This will execute the code defined in the thread concurrently with the main thread.
Here’s an example of how to create a thread by extending the Thread class:
public class MyThread extends Thread {
@Override
public void run() {
// Define the code to be executed in the thread
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
// Create and start the thread
MyThread myThread = new MyThread();
myThread.start();
}
}
In this example, we define a new class called MyThread that extends the Thread class. The MyThread class overrides the run() method, which contains the code that will be executed when the thread starts running.
We then create an instance of the MyThread class and start the thread by calling the start() method. When the start() method is called, the thread’s run() method is executed concurrently with the main thread.
Here’s an example of how to create a thread by implementing the Runnable interface:
public class MyRunnable implements Runnable {
@Override
public void run() {
// Define the code to be executed in the thread
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
// Create the Runnable object
MyRunnable myRunnable = new MyRunnable();
// Create the thread and start it
Thread myThread = new Thread(myRunnable);
myThread.start();
}
}
In this example, we define a new class called MyRunnable that implements the Runnable interface. The MyRunnable class also overrides the run() method, which contains the code that will be executed when the thread starts running.
We then create an instance of the MyRunnable class and pass it to the Thread constructor when creating a new thread. We start the thread by calling the start() method, which will execute the run() method concurrently with the main thread.
Overall, creating a thread in Java involves defining the code to be executed in the thread, creating an instance of the Thread class, and starting the thread using the start() method. Threads provide a powerful way to execute multiple tasks concurrently in a Java program.