In Java, a thread can be created in two main ways: by extending the `Thread` class or implementing the `Runnable` interface. Each method has its own advantages depending on the requirements of the application.
When you extend the `Thread` class, you override its `run()` method to define the code that should execute in the thread.
class MyThread extends Thread {
public void run() {
System.out.println("Thread using Thread class is running");
}
}
MyThread thread = new MyThread();
thread.start();
By implementing the `Runnable` interface, you can define your task in the `run()` method. This approach is often preferred as it allows your class to extend another class.
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread using Runnable interface is running");
}
}
Thread thread = new Thread(new MyRunnable());
thread.start();
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?