Bonjour,
J'essaie d'implémenter le diner des philosophes en utilisant les moniteurs de java mais seulement deux des 5 philosophes mangent.
Quelle est mon erreur ?
Merci !

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
 
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
 
public class Main {
static int nombreDePhilosophes = 5;
static int[] etats = new int[nombreDePhilosophes];
 
	public Main(){
 
	}
		public static void main(String[] args) {
			new Main();
			for (int i = 0; i < nombreDePhilosophes; i++) {
				new Thread(new Philo(i)).start();
			}
		}
}
 
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
 
 
public class Philo implements Runnable {
	int i;
	Lock lock;
	Condition[] eat = new Condition[Main.nombreDePhilosophes];
 
	public Philo(int i) {
		this.i=i;
		this.lock = new ReentrantLock();
		for(int j =0;j<Main.nombreDePhilosophes;j++){
			this.eat[j] = lock.newCondition();
		}
	}
 
	public void run() {
		new Philo(i);
		System.out.println("Le philosophe "+i+" est arrivé");
		while(true){
			prendre_une_fourchette(i);
			poser_fourchette(i);
		}
	}
 
	private void prendre_une_fourchette(int i) {
		lock.lock();
		try{
		while(Main.etats[(i+1)%Main.nombreDePhilosophes]==1 | Main.etats[(i-1+Main.nombreDePhilosophes)%Main.nombreDePhilosophes]==1 )
			try {
				Main.etats[i]=2;
				eat[i].await();
			} catch (InterruptedException e) {
			}
		Main.etats[i]=1;//mange		
		}finally{
			lock.unlock();
		}
		manger();
 
	}
 
 
	private void poser_fourchette(int i) {
		lock.lock();
		try{
		if(Main.etats[(i-1+Main.nombreDePhilosophes)%Main.nombreDePhilosophes]==2){
			eat[(i-1+Main.nombreDePhilosophes)%Main.nombreDePhilosophes].signal();
		}
		if(Main.etats[(i+1)%Main.nombreDePhilosophes]==2 ){
			eat[(i+1)%Main.nombreDePhilosophes].signal();
		}
		Main.etats[i]=0;//ne mange plus		
		}finally{
			lock.unlock();
		}
		pense();
 
	}
 
	private void pense() {
		System.out.println("Philosophe "+i+" est en train de penser.");
		long wait=(long)(Math.random()*1000);
		try {
			Thread.sleep(wait);
		} catch (InterruptedException e) {
		}
	}
 
	private void manger() {
		System.out.println("Philosophe "+i+" est en train de manger");
		long wait=(long)(Math.random()*1000);
		try {
			Thread.sleep(wait);
		} catch (InterruptedException e) {
		}
	}
}