Extending thread class and using thread methods
Extending thread class and using thread methods
Extending the Thread class and using its methods is a common way to create and manage threads in a multithreaded application in Java. When you extend the Thread class, you can override its run() method to define the code that should be executed in the new thread. Additionally, you can use various methods provided by the Thread class to control and manage the behavior of your threads.
Here's a step-by-step guide on how to do this:
1.Create a Java class that extends the Thread class:
public class MyThread extends Thread {
@Override
public void run() {
// Code to be executed in the new thread
for (int i = 0; i < 10; i++) {
System.out.println("Thread: " + Thread.currentThread().getId() + " Count: " + i);
}
}
}
2.Instantiate and start your custom thread:
You can create an instance of your custom thread class and then call the start() method to begin its execution.
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start();
thread2.start();
}
}
When you call start(), it invokes the run() method you defined in your MyThread class in a separate thread of execution.
Thread Methods
You can also use various methods provided by the Thread class to control and manage the behavior of threads. Some commonly used methods include:
sleep(long milliseconds): Pauses the execution of the current thread for the specified number of milliseconds.
join(): Waits for the thread to complete its execution before continuing with the current thread.
setName(String name): Sets the name of the thread.
getName(): Gets the name of the thread.
getId(): Gets the ID of the thread.
isAlive(): Checks if the thread is still alive (i.e., has not finished executing).
Here's an example of using the join() method to wait for a thread to finish:
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start();
thread2.start();
try {
thread1.join(); // Wait for thread1 to finish
thread2.join(); // Wait for thread2 to finish
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Both threads have finished.");
}
}
In this example, the join() method is used to wait for both thread1 and thread2 to finish before proceeding with the main thread.
Remember that extending the Thread class is just one way to create and manage threads in Java. Another common approach is to implement the Runnable interface and pass it to a Thread object, which provides more flexibility as you can implement multiple interfaces and extend other classes as needed.