Deadlocks

Philosophes


prend la fourchette à gauche
prend la fourchette à droite
mange pendant un certain temps
met les deux fourchettes à la table
pense 
pendant un certain temps

 

class Philosopher extends Thread{
Fork leftFork, rightFork;
Philosopher(String name,Fork left, Fork right){
super.setName(name);
leftFork=left;
rightFork=right;
start();
}
public void run(){
for(int i=0;i<2;i++){
leftFork.take();
System.out.println(getName()+" look for the second fork ");
try {
sleep((int)(Math.random()*2));
} catch (InterruptedException e){}

rightFork.take();
System.out.println(getName()+" eating ");
try {
sleep((int)(Math.random()*1000));
} catch (InterruptedException e){}
System.out.println(getName()+" poses the forks - thinking");
leftFork.pose();
rightFork.pose();
try {
sleep((int)(Math.random()*1000));
} catch (InterruptedException e1){}
}
System.out.println(getName()+" stop dinning");
}
}
class Fork{
private boolean taken;
private String name;
Fork(String name){
taken = false;
this.name=name;
}
synchronized void take(){
while(taken){
System.out.println(Thread.currentThread().getName()+" waiting for "+name);
try{ wait(); }
catch(InterruptedException e){
System.err.println(e);
}
}
System.out.println(Thread.currentThread().getName()+" take "+name);
taken = true;
}
synchronized void pose(){
taken = false;
notify();
}
public String toString(){
return name;
}
}
class Dinner{
public static void main(String arg[]){
int number=5;
Fork fk[]= new Fork[number];
for(int i=0;i<number;i++){
fk[i]= new Fork("fork "+i);
}
for(int i=0; i<number;i++){
new Philosopher("P"+(i+1),fk[i],fk[(i+1)%number]);
}
}
}
P1 take fork 0
P1 look for the second fork
P2 take fork 1
P2 look for the second fork
P3 take fork 2
P3 look for the second fork
P4 take fork 3
P4 look for the second fork
P5 take fork 4
P5 look for the second fork


L'approche le plus souvent utilisé pour éviter le deadlock est introduction une ordre prioritaire dans l'utilisation des resources.