u06-3
This commit is contained in:
parent
64fc30d444
commit
1d75699c81
|
@ -0,0 +1,32 @@
|
||||||
|
class Philosopher implements Runnable {
|
||||||
|
|
||||||
|
private Table t;
|
||||||
|
private int id;
|
||||||
|
public Philosopher(Table t, int id) {
|
||||||
|
this.t = t;
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void talk() {
|
||||||
|
System.out.println("Philosopher " + this.id + " is talking.");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void eat() {
|
||||||
|
System.out.println("Philosopher " + this.id + " is eating.");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public void run() {
|
||||||
|
talk();
|
||||||
|
|
||||||
|
try {
|
||||||
|
t.takeForks(this.id);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
eat();
|
||||||
|
|
||||||
|
t.returnForks(this.id);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
class PhilosophersTest {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
int numPhilosophers = 5;
|
||||||
|
|
||||||
|
Thread[] philosophers = new Thread[numPhilosophers];
|
||||||
|
Table t = new Table(numPhilosophers);
|
||||||
|
|
||||||
|
for (int i = 0; i < numPhilosophers; i++) {
|
||||||
|
philosophers[i] = new Thread(new Philosopher(t, i));
|
||||||
|
philosophers[i].start();
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < numPhilosophers; i++) {
|
||||||
|
try {
|
||||||
|
philosophers[i].join();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,33 @@
|
||||||
|
import java.util.concurrent.Semaphore;
|
||||||
|
|
||||||
|
class Table {
|
||||||
|
|
||||||
|
private int numForks;
|
||||||
|
private Semaphore[] forks;
|
||||||
|
|
||||||
|
public Table(int numForks) {
|
||||||
|
this.numForks = numForks;
|
||||||
|
|
||||||
|
this.forks = new Semaphore[numForks];
|
||||||
|
for (int i = 0; i < this.numForks; i++) {
|
||||||
|
this.forks[i] = new Semaphore(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void takeForks(int i) throws InterruptedException {
|
||||||
|
int left = i;
|
||||||
|
int right = (i + 1) % numForks;
|
||||||
|
if (right > left) {
|
||||||
|
forks[left].acquire();
|
||||||
|
forks[right].acquire();
|
||||||
|
} else {
|
||||||
|
forks[right].acquire();
|
||||||
|
forks[left].acquire();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void returnForks(int i) {
|
||||||
|
forks[i].release();
|
||||||
|
forks[(i + 1) % numForks].release();
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue