public class TestPhilo {
public static void main(String[] args) {
final int NB = 5;
Chopstick[] ctab = new Chopstick[NB];
Philo[] ptab = new Philo[NB];
for(int i = 0; i < NB; i++){
ctab[i] = new Chopstick();
}
for(int i = 0; i < NB; i++){
ptab[i] = new Philo(i, ctab[i], ctab[(i+1)%5]);
new Thread(ptab[i].start());
}
}
}
public class Chopstick {
private boolean libre = true;
public synchronized void prendre() throws InterruptedException{
while (!libre){
wait();
}
libre = false;
}
public synchronized void poser(){
libre = true;
notify();
}
}
import java.util.Random;
public class Philo implements Runnable{
private int id;
private Chopstick cd, cg;
private Random gen = new Random();
private void attendre() throws InterruptedException{
Thread.sleep(100+gen.nextInt(400));
}
public Philo(int id, Chopstick ch1, Chopstick ch2){
this.id = id;
cd = ch1;
cg = ch2;
}
public void run(){
try{
while(true){
attendre(); //penser
cg.prendre();
attendre();
cd.prendre();
attendre();
cd.poser();
attendre();
cg.poser();
}
}catch (InterruptedException e){
System.out.println("Philo"+id+"interrompu");
}
}
}
public class NewChopstick {
private boolean libre = true;
private Lock lock = new ReentrantLock();
public boolean prendre() throws InterruptedException{
return lock.tryLock();
}
public void poser(){
lock.unlock();
}
}
import java.util.Random;
public class NewPhilo implements Runnable{
private int id;
private Chopstick cd, cg;
private Random gen = new Random();
boolean leftOK = false, rightOK = false;
private void attendre() throws InterruptedException{
Thread.sleep(100+gen.nextInt(400));
}
public Philo(int id, Chopstick ch1, Chopstick ch2){
this.id = id;
cd = ch1;
cg = ch2;
}
public void run(){
try{
while(true){
try{
do{
try{
leftOK=cg.prendre();
rightOK=cd.prendre();
}finally{
if(!leftOK||!rightOK){
if(!leftOK){
cg.poser();
}
if(!rightOK){
cd.poser();
}
attendre();
}
}
} while(!leftOK||!rightOK);
attendre();
}finally{
cg.poser();
cd.poser();
}
}
}catch(InterruptedException e){
System.out.println("Interrompu");
}
}
}