HMD
HMD

Reputation: 460

Multi-threading in recursive methods

According to the following code:

synchronized int x(int y) {
    int m;

    class statement extends Thread {

            @Override
            void run() {
                //Some Statements    
                if (condition) {
                   m = x(someValue);
                }    
                //other statements
            }
     }
     //some statements

     statement st = new statement();
     st.start;
     return m;
}

every time that program invokes x(int y), it will create a new thread.

Now, When program invokes x() for the second time, the lock of the object is acquired by outer thread (the thread in the first invocation). So the thread in second invocation (inner thread) will acquire the object or it will be blocked?

Regards

Upvotes: 0

Views: 893

Answers (1)

GhostCat
GhostCat

Reputation: 140613

That keyword there makes sure that only one thread can invoke x() at any point in time.

But: you can't predict if the outer thread is still within that method or not.

And just for the record: don't do that. Don't write "real" code like this.

Upvotes: 1

Related Questions