In this lesson, you will learn.
As we stated earlier, Threads can be created in two ways
In this lesson, you will learn the second approach to create a Thread
Creating a new thread by Implementing a Runnable Interface includes the following 3 steps.

class Counter implements Runnable {
// Body of a Class
}
@Override
public void run() {
//Body of the Thread
}
Counter counter1 = new Counter("Counter 1");
Thread t1 = new Thread(counter1);
t1.start();
package usingrunableinterface;
//Define a class that implements the Runnable interface
class Counter implements Runnable {
private String name;
public Counter(String name) {
this.name = name;
}
// The run method contains the code that will be executed by the thread
public void run() {
for (int i = 1; i <= 5; i++) {
try {
// Sleep for a second to simulate work
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(name + " has been interrupted.");
}
System.out.println(name + ": " + i);
}
System.out.println(name + " has finished counting.");
}
}
public class ThreadUsingRunnable {
public static void main(String[] args) {
// Create instances of the Runnable object
Counter counter1 = new Counter("Counter 1");
Counter counter2 = new Counter("Counter 2");
// Create two threads from those instances
Thread thread1 = new Thread(counter1);
Thread thread2 = new Thread(counter2);
// Start the threads
thread1.start();
thread2.start();
try {
// Wait for both threads to finish
thread1.join();
thread2.join();
} catch (InterruptedException e) {
System.out.println("Main thread was interrupted.");
}
System.out.println("Main thread has finished.");
}
}
Counter 2: 1
Counter 1: 1
Counter 1: 2
Counter 2: 2
Counter 2: 3
Counter 1: 3
Counter 1: 4
Counter 2: 4
Counter 2: 5
Counter 1: 5
Counter 2 has finished counting.
Counter 1 has finished counting.
Main thread has finished.
Counter 1: 1
Counter 2: 1
Counter 1: 2
Counter 2: 2
Counter 2: 3
Counter 1: 3
Counter 1: 4
Counter 2: 4
Counter 1: 5
Counter 2: 5
Counter 2 has finished counting.
Counter 1 has finished counting.
Main thread has finished.
Runnable interface, which requires the implementation of the run() method. The name attribute is used to identify the thread in the output.Counter objects are created, each initialized with a different name.Thread instances. Both threads are started with the start() method.join() method is called on each thread to ensure that the main thread waits for both of these threads to complete before it continues and prints its final message.
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.