如何锁定/解锁资源?

时间:2014-10-06 15:48:17

标签: language-agnostic synchronization locking

query的前两部分已在link中得到解决,并希望在实施之前了解有关第三部分的更多内容。

第III部分(3分)

    Implement a "lockable" doubly-linked list ADT: a list in which any node can be "locked." A locked node can never be removed from its list. Any attempt to remove a locked node has no effect (not even an error message). Your locked list classes should be in the list package alongside DList and DListNode.

    First, define a LockDListNode class that extends DListNode and carries information about whether it has been locked. LockDListNodes are not locked when they are first created. Your LockDListNode constructor(s) should call a DListNode constructor to avoid code duplication.

    Second, define a LockDList class that extends DList and includes an additional method

        public void lockNode(DListNode node) { ... }

    that permanently locks "node".
    Your LockDList class should override just enough methods to ensure that
    (1) LockDListNodes are always used in LockDLists (instead of DListNodes), and
    (2) locked nodes cannot be removed from a list.

WARNING: To override a method, you must write a new method in the subclass with EXACTLY the same prototype. You can’t change a parameter’s type to a subclass. Overriding won’t work if you do that.

Your overriding methods should include calls to the overridden superclass methods whenever it makes sense to do so. Unnecessary code duplication will be penalized.

使用任何现有的Java包理解lockingunlocking一个DListNode 而不非常重要。使用boolean flag;成为LockDListNode成员来表示锁定/解锁状态的方法,此标志的设置是非原子的。因为,如果我设置flag = true;,则此设置操作可以是字节代码级别的多行指令。

一旦解决了成为实施lock/unlock的瓶颈的问题,就可以在此之后轻松处理继承和覆盖内容。

我的问题:

您能否建议在lock/unlock上实施DListNode功能的方法?

注意:此查询与Java知识无关。

1 个答案:

答案 0 :(得分:1)

新类LockDListNode将扩展DListNode。现在你需要了解继承。 DListNode应该有一个删除操作方法,你需要覆盖该方法,不要做任何事情。
请参阅下面的代码模板:

public class DListNode {
    public DListNode{
    }

    public void delete(){
          // TODO some delete code here
    }
}

public class LockDListNode extends DListNode {
    public LockDListNode{
        super();
    }

    @override
    public void delete(){
        // DO nothing here
    }
}

现在,如果你这样做

DListNode unableToDeleteNode =  new LockDListNode();
unableToDeleteNode.delete();

您创建了一个LockDListNode对象并调用delete方法,它将调用LockDListNode的删除而不是DListNode。