public class MyRunnable implements Runnable {
@Override
public void run() {
// This method runs in a separate thread
try {
// Some long-running operation
for (int i = 0; i < 5; i++) {
System.out.println("Running in thread: " + Thread.currentThread().getName());
Thread.sleep(1000); // Sleep for a second
}
} catch (InterruptedException e) {
// Common mistake: Not handling InterruptedException correctly
System.err.println("Thread was interrupted!");
}
}
public static void main(String[] args) {
// Common mistake: Not starting the thread properly
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
// Starting the thread
thread.start();
// Common mistake: Not checking if the thread has finished running
try {
thread.join(); // Wait for the thread to finish
} catch (InterruptedException e) {
System.err.println("Main thread was interrupted!");
}
System.out.println("Main thread finished.");
}
}
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?