Will this code not result in a deadlock? Java Threads locking
So the thing is, I want to be able to do this with my class.
object.lockAccess(); object.doSomething(); object.doAnotherThing(); object.doAnotherThingYet(); object.unlockAccess();
So the other thread will not be able to access my class methods while locked. Here is the implementation I did, I was wondering if someone got a better idea, or if it may fail.
p开发者_开发问答rivate boolean locked = false;
public void lockAccess() throws Exception
{
while(!tryToLock())
{
Thread.sleep(1000);
}
}
public void unlockAccess() throws Exception
{
while(!tryToUnlock())
{
Thread.sleep(1000);
}
}
private synchronized boolean tryToLock()
{
if(locked)
return false;
else
{
locked = true;
return true;
}
}
private synchronized boolean tryToUnlock()
{
if(locked)
return false;
else
{
locked = false;
return true;
}
}
while(!tryToLock())
{
Thread.sleep(1000);
}
Terrible idea.
Use a Lock implementation from java.util.concurrent.
Or just a synchronized
block.
Based on your intent it'd be far easier to just do this (since you can use any object as a mutex in Java):
synchronized( object ) {
object.doSomething();
object.doAnotherThing();
object.doAnotherThingYet();
}
If you need finer control, and a tryLock in particular, then look at the "Lock" interface and the classes that implement it.
Your tryToUnlock()
method is incorrect, but otherwise it would technically work.
Most Java programmers would do something more like this, though:
synchronized (object) {
object.doSomething();
object.doSomethingElse();
...
}
精彩评论