Java Exercise
In this exercise, you will create a Java program that demonstrates the use of the **Thread** and **Runnable** classes to run multiple threads. First, you will implement a class that implements the **Runnable** interface, and then you will create a **Thread** object to execute your code in parallel. Next, you will use the **Thread** class directly to manage threads. Throughout this exercise, you'll see how both options allow you to execute code concurrently, improving your application's performance.
Instructions:
- Create a class that implements the
Runnable
interface and override the run()
method to define the task to be executed.
- Create an object of the
Thread
class, passing the Runnable
object as a parameter, and call the start()
method to execute the thread.
- Implement another thread using the
Thread
class directly and override the run()
method to perform the task.
- In the main method, create and run both threads to demonstrate their functionality.
This exercise will help you understand how to handle concurrency using **Thread** and **Runnable**, two of the most common methods for working with threads in Java, will allow you to perform tasks efficiently in concurrent applications.
View Example Code
// Class implementing Runnable
class MyRunnableTask implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Runnable Thread: " + i);
try {
Thread.sleep(500); // Simulates work in the thread
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
}
// Class extending Thread
class MyThread extends Thread {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread Class: " + i);
try {
Thread.sleep(500); // Simulates work in the thread
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
}
public class Main {
public static void main(String[] args) {
// Create and start the thread using Runnable
MyRunnableTask runnableTask = new MyRunnableTask();
Thread runnableThread = new Thread(runnableTask);
runnableThread.start();
// Create and start the thread using Thread
MyThread threadClass = new MyThread();
threadClass.start();
}
}
Output:
Runnable Thread: 1
Thread Thread: 1
Runnable Thread: 2
Thread Thread: 2
Runnable Thread: 3
Thread Thread: 3
Runnable Thread: 4
Thread Thread: 4
Runnable Thread: 5
Thread Thread: 5
This program demonstrates how to create and run threads in Java using both the Thread
class and the Runnable
interface. The thread created using Runnable
and the thread created by extending the Thread
class run tasks concurrently, demonstrating how to work with threads to perform tasks concurrently in Java.