Professional Documents
Culture Documents
package com.asosyalbebe.deadlock;
public class Philosopher extends Thread implements Runnable {
private int forkLeft;
private int forkRight;
private int index;
public Philosopher(int index) {
forkLeft = index;
forkRight = (index + 1) % 5;
this.index = index;
}
@Override
public void run() {
// Endless life of a philosopher
while (true) {
takeForks();
eat();
putDownForks();
think();
}
}
/* Take left and right forks */
private void takeForks() {
System.out.printf("Filozof#%d is taking forks\n", index);
Table.takeFork(forkLeft);
System.out.printf("Filozof#%d took fork at left\n", index);
Table.takeFork(forkRight);
System.out.printf("Filozof#%d took fork at right\n", index);
}
/* Put left and right forks down */
private void putDownForks() {
System.out.printf("Filozof#%d is putting forks down\n", index);
Table.putDownFork(forkLeft);
System.out.printf("Filozof#%d put left fork down\n", index);
Table.putDownFork(forkRight);
System.out.printf("Filozof#%d put right fork down\n", index);
}
/* Eat for a while */
private void eat() {
System.out.printf("Filozof#%d is now eating\n", index);
sleep();
}
/* think for a while */
private void think() {
System.out.printf("Filozof#%d is now thinking\n", index);
sleep();
}
private void sleep() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Table sınıfında (main methodu bu sınıfta) filozoflar yaratılıp hepsi ayrı thread olarak başlatılır.
Ayrıca çatallar da bu sınıf içerisinde yaratıılır ve filozoflar istediği zaman bu sınıftan istiyorlar.
Lock/unlock mekanizması da bu sınıf içerisinde bulunuyor.
package com.asosyalbebe.deadlock;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Table {
public static Lock[] forks;
public static Philosopher[] philosophers;
public static void main(String[] args) {
philosophers = new Philosopher[5];
forks = new Lock[5];
for (int i = 0; i < philosophers.length; i++) {
philosophers[i] = new Philosopher(i);
forks[i] = new ReentrantLock();
}
for (int i = 0; i < philosophers.length; i++) {
philosophers[i].start();
}
}
/* Locks a fork with given index
* @param fork index of the fork */
public static void takeFork(int fork) {
forks[fork].lock();
}
/* unlocks a fork with given index
* @param fork index of the fork */
public static void putDownFork(int fork) {
forks[fork].unlock();
}
}