简体   繁体   中英

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?

The constructor isn't accepting a run method (eg, 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");  
        }  
    }  
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM