使用Mutex实现线程安全的链表功能

1、Mutex是个简单的互斥排它锁
2、Node是链表的节点,没有节点都持有自己的Mutex锁
3、List是链表,在search方法中通过对节点的加锁和解锁达到同步的目的

public class Mutex {

/** 是否锁定的状态位 **/
protected boolean inuse_ = false;

public void acquire() throws InterruptedException {
if (Thread.interrupted()) throw new InterruptedException();
synchronized(this) {
try {
while (inuse_) wait();
inuse_ = true;
}
catch (InterruptedException ex) {
notify();
throw ex;
}
}
}

public synchronized void release() {
inuse_ = false;
notify();
}

}

class Node {
Object item; //节点对象,实际使用时可以用领域对象进行替换
Node next;
Mutex lock = new Mutex(); // 每个节点都保存自己的锁对象

Node(Object x, Node n) { item = x; next = n; }
}

class List {
protected Node head;

protected synchronized Node getHead() { return head; }

boolean search(Object x) throws InterruptedException {
Node p = getHead();
if (p == null) return false;


p.lock.acquire(); // 先加锁,再循环

for (;;) {
if (x.equals(p.item)) {
p.lock.release(); // 找到直接释放锁
return true;
}
else {
Node nextp = p.next;
if (nextp == null) {
p.lock.release(); // 没有找到对象,也要释放锁
return false;
}
else {
try {
nextp.lock.acquire(); // 给链表下一个节点加锁
}
catch (InterruptedException ex) {
p.lock.release(); // 加锁如果失败,也要释放前一个节点的锁
throw ex;
}
p.lock.release(); // 加锁成功,释放前一个节点的锁
p = nextp;
}
}
}
}

synchronized void add(Object x) { // simple prepend
head = new Node(x, head);
}

// ...
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值