死锁
某个任务在等待另一个任务,而后者又在等待别的任务,这样一直下去,直到这个链上的任务又在等待第一个任务释放锁,这样就得到一个任务之间互相等待的连续循环, 没有哪个任务可以继续,这种情况就称为死锁。
死锁发生的条件
死锁必须同时满足一下四个条件才能发生:
1. 互斥条件。
2. 请求与保持。至少有一个任务必须持有一个资源且正在等待获取一个当前被别到任务持有到资源;
3. 资源不能被任务抢占,任务必须把资源的释放当成普通事件。
4. 必须有循环等待。
class Chopstick {
private boolean taken = false;
public synchronized void take() throws InterruptedException {
while(taken) {
wait();
}
taken = true;
}
public synchronized void drop() throws InterruptedException {
taken = false;
notifyAll();
}
}
class Philosopher implements Runnable {
private Chopstick left;
private Chopstick right;
private final int id;
private final int ponderFactor;
private Random rand = new Random(47);
private void pause() throws InterruptedException {
if (ponderFactor == 0)
return;
TimeUnit.MILLISECONDS.sleep(rand.nextInt(ponderFactor * 250));
}
public Philosopher(Chopstick left, Chopstick right, int ident, int ponder) {
this.left = left;
this.right = right;
id = ident;
ponderFactor = ponder;
}
@Override
public void run() {
try {
while (!Thread.interrupted()) {
System.out.println(this + " " + " thinking...");
pause();
System.out.println(this + " grab the left chopostick.");
left.take();
System.out.println(this + " grab the right chopostick.");
right.take();
System.out.println(this + " eat.");
left.drop();
right.drop();
}
} catch (InterruptedException e) {
System.out.println(this + " exits via interrupt.");
}
}
@Override
public String toString() {
return "Philosopher " + id;
}
}
public class DeadLockPhilosopher {
public static void main(String[] args) throws Exception {
int ponder = 5;
if (args.length > 0) {
ponder = Integer.parseInt(args[0]);
}
int size = 5;
if (args.length > 1) {
size = Integer.parseInt(args[1]);
}
ExecutorService exec = Executors.newCachedThreadPool();
Chopstick[] sticks = new Chopstick[size];
for (int i = 0; i < size; i++) {
sticks[i] = new Chopstick();
}
for (int i = 0; i < size; i++) {
exec.execute(new Philosopher(sticks[i], sticks[(i+1) % size], i, ponder));
}
if (args.length == 3 && args[2].equals("timeout")) {
TimeUnit.SECONDS.sleep(5);
} else {
System.out.println("press 'enter' to quit.");
System.in.read();
}
exec.shutdownNow();
}
}