I am trying to learn threading, and regarding the following example
public class LockExample {
private Lock lockone = new ReentrantLock();
public void method1() {
lockone.lock();
try {
// do something
} finally {
lockone.unlock();
}
}
public void method2() {
lockone.lock();
try {
// do something
} finally {
lockone.unlock();
}
}
}
does it mean that if we lock
method1andmethod2using the same lock, say threadAandBcan not accessmethod1ormethod2at the same time. But if we lockmethod1andmethod2using different lockslockoneandlocktwo, then threadAcan accessmethod1, at the same time threadBcan accessmethod2?why don't we lock each method separately instead of putting them in one lock?
public class LockExample {
private Lock lockone = new ReentrantLock();
public void method1() {
lockone.lock();
try {
// do something
} // wrap the two methods in one lock?
}
public void method2() {
try {
// do something
} finally {
lockone.unlock();
}
}
}
}
method2without holding the lock (i.e. without having previously calledmethod1) thenIllegalMonitorStateExceptionis thrown.