How can a Thread constructor accept a start method directly?
I referenced DeadLock code and saw this site
http://www.javatpoint.com/deadlock-in-java
I've seen the java API but couldn't find such a thread constructor and was still wondering how does this compile in the Eclipse IDE?
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};
How can a Thread constructor accept a start method directly?
source to share
The constructor does not accept a method run
(like as an argument), this code creates an anonymous class, see this tutorial . Behind the scenes, an unnamed class (anonymous class) is created that derives from Thread
and overrides the method run
; then an instance of this class is created and assigned to a variable t1
.
Just for completeness: although as of Java 8, a constructor Thread
can (essentially) take a function run
as an argument because of the Java 8 lambda functions. It looks like this:
Thread t = new Thread(() -> {
System.out.println("Running");
});
This is possible because it Thread
has a constructor that takes an instance Runnable
and Runnable
is a functional interface (an interface that only defines one function), and so you can instantiate that interface simply using a lambda and then pass that to the constructor Thread
. There is a tutorial on lambdas here . But that's not what the quoted code does.
Here is the code in your question, using a lambda instead of an anonymous class:
Thread t1 = new Thread(() -> {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
});
source to share