Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can two threads run two different methods at the same point of time?

class A {
    private synchronized f() {
        ...
        ...
    }

    private void g() {
        ...
        ...
    }
}

If thread T1 is running f() which is synchronized, can thread t2 run g() which is not synchronized at the same point of time, while T1 is still running f()?

like image 250
Kalyan Ghosh Avatar asked Sep 07 '10 19:09

Kalyan Ghosh


People also ask

Can two threads execute two methods?

Q6) Can two threads call two different static synchronized methods of the same class? Ans) No. The static synchronized methods of the same class always block each other as only one lock per class exists.So no two static synchronized methods can execute at the same time.

Can 2 threads run at the same time?

In the same multithreaded process in a shared-memory multiprocessor environment, each thread in the process can run concurrently on a separate processor, resulting in parallel execution, which is true simultaneous execution.

Can two threads at same time execute two different methods one is static synchronized and second is only synchronized method?

Indeed, it is not possible! Hence, multiple threads will not able to run any number of synchronized methods on the same object simultaneously.

Can two threads access two different synchronized methods on an object?

First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.


2 Answers

Not on the same instance of A. The instance itself is the lock so two execute the two methods at the same time with two threads you would need two instances of A.

like image 99
willcodejavaforfood Avatar answered Oct 19 '22 14:10

willcodejavaforfood


Yes. Both methods can execute at the same time on the same instance.

Only f() is synchronized. A thread must acquire the monitor for this.f() to execute f() and only one monitor exists per instance.

g() is not synchronized, no monitor locking is required to run the method, so any thread can execute g() at any time.

"A synchronized method acquires a monitor (§17.1) before it executes."

http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.3.6

like image 32
reassembler Avatar answered Oct 19 '22 14:10

reassembler