Pawan
Pawan

Reputation: 32331

How can a Thread constructor can accept a run method directly?

I was refering to DeadLock code and saw this website

http://www.javatpoint.com/deadlock-in-java

I saw the java API, but couldn't find any such Thread Constructor and still wondering how is this being compiled in 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 can accept a run method directly?

Upvotes: 3

Views: 100

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074585

The constructor isn't accepting a run method (e.g., as an argument), that code is creating an anonymous class, see this tutorial. Behind the scenes, a class with no name (anonymous class) is created that derives from Thread and overrides the run method; then an instance of that class is created and assigned to the t1 variable.


Just for completeness, though: As of Java 8, it is possible for the Thread constructor to (in effect) accept a run function as an argument, because of Java 8's lambda functions. That looks like this:

    Thread t = new Thread(() -> {
        System.out.println("Running");
    });

This is possible because Thread has a constructor accepting a Runnable instance, and Runnable is a functional interface (an interface that only defines a single function), and so you can create an instance implementing that interface simply by using a lambda and then pass that into the Thread constructor. There's a tutorial on lambdas here. But that's not what the quoted code is doing.

Here's 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");  
        }  
    }  
});

Upvotes: 4

Related Questions