Imagine the following implementation of your Runnable. A simple class that implements an interface.
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(i + " runnable thread...");
}
}
}
So, in order to create your Thread the way you intended you must provide an implementation of a Runnable object. There are various ways to achieve this.
The most straightforward approach is perhaps to use an instance of the Runnable from above:
Thread t1 = new Thread(new MyRunnable());
An alternative to that is to provide the Runnable directly in the code as an anonymous inner class which you can find out more about here.
An anonymous inner class simply means that you create a class as an expression in the code where you mean to use it - the class must follow the same signature (i.e. in this case it implements the Runnable interface).
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(i + " runnable thread...");
}
}
});
From the Oracle Docs:
The anonymous class expression consists of the following:
- The new operator
- The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface HelloWorld.
- Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.
- A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.
So, basically what you are doing is passing a Runnable to your Thread constructor. If you are passing it as an anonymous class you simply pass it as an expression where you actually define your entire inner class.
Furthermore, in Java 8 you can replace the anonymous inner class with a lambda expression like this:
Thread t3 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println(i + " runnable thread...");
}
});