In Java, the Runnable
interface is used to define a task that can be executed by a thread. When a class implements the Runnable
interface, it must override the run()
method, where the code to be executed by the thread will be placed. Multiple threads can be created to run the same instance of a Runnable
object, allowing for concurrent execution of tasks. This behavior is essential in multithreaded applications, as it provides a way to perform operations in parallel, improving efficiency and responsiveness.
Here is a simple example of how the Runnable
interface can be used in a multithreaded environment:
class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " is executing task " + i);
try {
Thread.sleep(100); // Simulating work
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
Thread thread1 = new Thread(new MyRunnable(), "Thread 1");
Thread thread2 = new Thread(new MyRunnable(), "Thread 2");
thread1.start();
thread2.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?