If you need to create a Thread in Java, and cannot extend the Thread class, often because you are extending another class, you can always implement Runnable
.
public class RunnableExample implements Runnable {
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
RunnableExample obj = new RunnableExample();
Thread thread = new Thread(obj);
thread.start();
System.out.println("This code is outside of the thread");
}
}
public void run() {
System.out.println("This code is running in a thread");
}
}
Notice, that just like where you extend the Thread class, you have to override the abstract method run
.
However, in this example, you need to create a Thread object, and pass in your object that implements Runnable to its constructor. Then you can call that thread’s object’s start() method, to start the thread and run what’s in run.
Once again, your thread is going to be what’s inside of run, and often is a conditional loop to allow the thread to keep doing what it is supposed to do.
Java Threads – Implementing Runnable was originally found on Access 2 Learn