I am new to mutli-threading in java and trying to understand the keyword synchronization
I have following code:
class LockObject {
int threadsGoingThrough = 0;
synchronized void locked() {
threadsGoingThrough++;
try {
wait(1000);
} catch (Exception e) {
System.out.println("Exception " + e);
}
if (threadsGoingThrough > 1) {
System.out.print(" !! ouups !! ");
}
;
threadsGoingThrough--;
}
}
The Thread-class:
class LockTester extends Thread {
LockObject myLock;
String message;
public void run() {
while (true) {
myLock.locked();
System.out.print(message);
}
}
}
My main looks like this:
LockObject theLock = new LockObject();
LockTester threadA = new LockTester();
threadA.myLock = theLock;
threadA.message = "A";
LockTester threadB = new LockTester();
threadB.myLock = theLock;
threadB.message = "B";
threadA.start();
threadB.start();
If I run this code now in two threads than it gives the following ouput:
!! ouups !! A !! ouups !! B !! ouups !! A !! ouups !! B !! ouups !! A !! ouups !! B
The !! ouups !! should only occurs when two threads are in the synchronized method at the same time. How can this happen?
You’re calling
wait(), which will release the lock of the monitor it’s called on. It will then reacquire the lock when it wakes up (either due to timeout or the monitor being notified). If you were just trying to sleep for a second, useThread.sleep(1000)which won’t release any locks.