Reputation:
// Runnable cannot instantiate
public class Thread4 {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable());
}
}
//Runnable cannot instantiate
Why? Although in the other program it's instantiating with the same code.
Upvotes: 0
Views: 1312
Reputation: 111
Directly you can't pass new Runnable() inside new Thread(). You need to create an implemented class (for example : MyTestRunnable.java) which implement Runnable Interface and pass new MyTestRunnable() in new Thread().
public class MyTestRunnable implements Runnable {
public void run(){
System.out.println(" .... ");
}
}
public class Thread4 {
public static void main(String[] args) {
Thread t1 = new Thread(new MyTestRunnable());
}
}
Upvotes: 2
Reputation: 393781
Runnable
is an interface, not a class. In order to instantiate it, you must supply a class that implements the interface (or a lambda expression or method reference if you are using Java 8 or later).
For example:
Thread t1 = new Thread(new Runnable() {public void run() {}});
Here I defined an anonymous class that implements Runnable
and created an instance of that class.
Upvotes: 3