您的位置:首页 > 其它

《Cracking the Coding Interview》——第16章:线程与锁——题目3

2014-04-27 19:40 447 查看
2014-04-27 19:26

题目:哲学家吃饭问题,死锁问题经典模型(专门用来黑哲学家的?)。

解法:死锁四条件:1. 资源互斥。2. 请求保持。3. 非抢占。4. 循环等待。所以,某砖家拿起一只筷子后如果发现没有另一只了,就必须把手里这只筷子放下,这应该是通过破坏“请求保持”原则来防止死锁产生,请求资源失败时,连自己的资源也进一步释放,然后在下一轮里继续请求,直到成功执行。

代码:

// This is the class for chopsticks.
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Chopstick {
private Lock lock;

public Chopstick() {
lock = new ReentrantLock();
}

public boolean pickUp() {
return lock.tryLock();
}

public void putDown() {
lock.unlock();
}
}

//------------------------------------I'm a delimiter------------------------------------
// This is the class for philosophers.
import java.util.Vector;

public class Philosopher extends Thread {
private Chopstick left;
private Chopstick right;
private int id;
int appetite;

final int FULL_APPETITE = 10;

public Philosopher(Chopstick left, Chopstick right, int id) {
// TODO Auto-generated constructor stub
appetite = 0;
this.left = left;
this.right = right;
this.id = id;
}

private boolean pickUp() {
if (!left.pickUp()) {
return false;
}
if (!right.pickUp()) {
left.putDown();
return false;
}
return true;
}

private void putDown() {
left.putDown();
right.putDown();
}

public boolean eat() {
while (appetite < FULL_APPETITE) {
if (!pickUp()) {
return false;
}
System.out.println(id + ":chew~");
++appetite;
putDown();
}
return appetite == FULL_APPETITE;
}

@Override
public void run() {
// TODO Auto-generated method stub
super.run();
while (!eat()) {
// Not full yet.
}
}

public static void main(String[] args) {
final int n = 6;
Vector<Chopstick> chopsticks = new Vector<Chopstick>();
Vector<Philosopher> philosophers = new Vector<Philosopher>();

for (int i = 0; i < n; ++i) {
chopsticks.add(new Chopstick());
}
for (int i = 0; i < n; ++i) {
philosophers.add(new Philosopher(chopsticks.elementAt(i),
chopsticks.elementAt((i + 1) % n), i + 1));
}

for (int i = 0; i < n; ++i) {
philosophers.elementAt(i).start();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐