In Java, a thread is defined as a lightweight process that runs concurrently with other threads within a single JVM (Java Virtual Machine). Each thread has its own call stack and can execute a separate path of code, potentially sharing data and resources with other threads.
To create a thread in Java, you can either extend the Thread class or implement the Runnable interface. 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.
Alternatively, you can create a thread by implementing the Runnable interface. 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, a thread in Java is defined as a lightweight process that runs concurrently with other threads within a single JVM. Threads can be created by extending the Thread class or implementing the Runnable interface, and they provide a powerful way to execute multiple tasks concurrently in a Java program.