A thread in Java is a separate execution path that can run concurrently with other threads in the same program. Each thread has its own call stack and can execute its own code independently of other threads.
Threads can be created in Java in two ways: by extending the Thread class or by implementing the Runnable interface. The Runnable interface is preferred because it allows for greater flexibility and reuse of code.
To create a thread using the Runnable interface, you can follow these steps:
- Create a class that implements the Runnable interface and override its run() method.
- In the run() method, write the code that you want the thread to execute.
- Create an instance of the class that implements the Runnable interface.
- Create a new Thread object and pass the instance of the class that implements the Runnable interface to the Thread constructor.
- Call the start() method on the Thread object to start the thread.
Here is an example of creating a thread using the Runnable interface to display numbers from 1 to 20, with each number displayed in an interval of 2 seconds:
public void run() {
for (int i = 1; i <= 20; i++) {
System.out.println(i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
NumberPrinter numberPrinter = new NumberPrinter();
Thread thread = new Thread(numberPrinter);
thread.start();
}
}
In this example, the NumberPrinter class implements the Runnable interface and overrides the run() method to print the numbers from 1 to 20, with a 2-second interval between each number. The Main class creates an instance of NumberPrinter and passes it to a new Thread object, which is started with the start() method. This starts the execution of the run() method in a separate thread, allowing the numbers to be printed with a 2-second delay between each number.
No comments:
Post a Comment
If you have any doubts, please let me know