Добрый день. Пытаюсь реализовать задачу об обедающих философах на Java под Android. Реализовать необходимо используя семафоры. Текущий исходный код приведен ниже.
Java |
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
| public class Philosopher extends Thread implements Fork {
String name;
int indexOfForkLeft;
int indexOfForkRight;
public Philosopher(String name, int indexOfForkLeft, int indexOfForkRight) {
this.name = name;
this.indexOfForkLeft = indexOfForkLeft;
this.indexOfForkRight = indexOfForkRight;
}
@Override
public void run() {
while (!((forks[indexOfForkLeft].availablePermits() == 1) &&
(forks[indexOfForkRight].availablePermits() == 1))) {
//wait
}
eat();
releaseForks();
}
private void eat() {
try {
forks[indexOfForkLeft].acquire(1);
forks[indexOfForkRight].acquire(1);
System.out.println(name + " -----eating");
sleep(5000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
private void releaseForks() {
forks[indexOfForkLeft].release(1);
forks[indexOfForkRight].release(1);
}}
// Main class
public class MainThred {
public static void main(String[] args) throws InterruptedException {
Philosopher philosopher_1 = new Philosopher("Philosopher_1", 1, 0);
Philosopher philosopher_2 = new Philosopher("Philosopher_2", 2, 1);
Philosopher philosopher_3 = new Philosopher("Philosopher_3", 3, 2);
Philosopher philosopher_4 = new Philosopher("Philosopher_4", 4, 3);
Philosopher philosopher_5 = new Philosopher("Philosopher_5", 0, 4);
philosopher_1.start();
philosopher_2.start();
philosopher_3.start();
philosopher_4.start();
philosopher_5.start();
}}
// интерфейс с массивом вилок
public interface Fork {
Semaphore[] forks = {new Semaphore(1), new Semaphore(1), new Semaphore(1), new Semaphore(1), new Semaphore(1)};}
Вывод в консоль следующий :
Philosopher_1 -----eating
Philosopher_3 -----eating
Philosopher_5 -----eating
Philosopher_2 -----eating
Philosopher_4 -----eating |
|
Это есть пример одного обеда философов когда одновременно могут есть только двое. Данная очередность выполнения потоков мне подходит. Единственное что нужно сделать - выполнять данный "цикл" заданное количество раз, т.е повторять обед нужное количество раз. Подскажите какими средствами Java и Android можно добиться результата?Спасибо.