Pergunta

Searching for solution to identify concrete method execution at time. Do not understand name of method, but concrete execution of method. For example in case of recursive calling in two threads at same time on same object of same method, if it's possible.

Foi útil?

Solução

It is possible to call a static method aswell as a method of an instance from different threads at the same time.

Although should you take care of race-conditions aswell as general problems caused by accessing and modifiying objects, which are shared between those threads (generally all static objects aswell as instance members if two threads use the same instance of a class)

Synchronizing access to shared objects is possible with the following code:

public class Calculator {
    private int c;

    public void increment() {
        synchronized(c) {
            c++;
        }
    }
}

More informations: http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html

Synchronizing access to shared methods is possible with the following code:

public synchronized void increment() {
        c++;
    }

More informations: http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html

Something a bit more advanced, which allows you to reach a better performance would be a ReadWriteLock, but you won't need that for now.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top