Threads ReentrantLock mehrfach verwenden

RungetSvohu

Bekanntes Mitglied
Hallo,

ich habe eine kleine Rückfrage, um sicherzugehen, dass ich alles richtig verstanden habe. Am Anfang einer Klasse habe ich
Java:
private final Lock lock = new ReentrantLock();

Nun habe ich im Code sowas:
Java:
lock.lock();
//Code 1
...
lock.unlock();

Java:
lock.lock();
//Code 2
...
lock.unlock();

Sehe ich das richtig, dass niemals Code 1 und Code 2 gleichzeitig ausgeführt werden können, weil ich das selbe ReentrantLock-Objekt verwende?
 
Javadoc sagt

javadoc hat gesagt.:
Acquires the lock.
Acquires the lock if it is not held by another thread and returns immediately, setting the lock hold count to one.

If the current thread already holds the lock then the hold count is incremented by one and the method returns immediately.

If the lock is held by another thread then the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired, at which time the lock hold count is set to one.

..also ja!
 
Javadoc sagt
..also ja!
Hätte ja auch sein können, dass niemals Code 1 zweimal gleichzeitig ausgeführt wird und niemals Code 2 zweimal gleichzeitig ausgeführt wird, aber es sehr wohl möglich ist, dass Code 1 und Code 2 gleichzeitig ausgeführt werden. Wenn ich ersteres will, muss ich es dann so machen, denke ich:

Java:
private final Lock lock1 = new ReentrantLock();
private final Lock lock2 = new ReentrantLock();

Java:
lock1.lock();
//Code 1
...
lock1.unlock();

Java:
lock2.lock();
//Code 2
...
lock2.unlock();

Richtig?
 
Zuletzt bearbeitet:

Zurück
Oben