package CareerCup;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Chopstick {
private Lock lock;
Chopstick() {
lock = new ReentrantLock();
}
public boolean pickUp() {
return lock.tryLock();
}
public void putDown() {
lock.unlock();
}
}
class Philosopher extends Thread{
private Chopstick left;
private Chopstick right;
int bites = 3;
private String name;
Philosopher(Chopstick l, Chopstick r, String n) {
this.left = l;
this.right = r;
name = n;
}
public boolean eat() {
if(!left.pickUp()) {
return false;
}
if(!right.pickUp()) {
left.putDown();
return false;
}
chew();
left.putDown();
right.putDown();
return true;
}
void chew() {
for(int i = 1; i <= bites; i++)
System.out.println(name + " is chewing " + i + "th bite");
}
public void run() {
eat();
}
}
public class PhilosopherDinner {
/**
* @param args
*/
public static void main(String[] args) {
Chopstick sticks[] = new Chopstick[3];
Philosopher phis[] = new Philosopher[3];
for(int j = 0; j < sticks.length; j++)
sticks[j] = new Chopstick();
for(int i = 0; i < phis.length; i++) {
if(0 == i) {
phis[i] = new Philosopher(sticks[sticks.length - 1], sticks[0], 0 + "");
}
else {
phis[i] = new Philosopher(sticks[i - 1], sticks[i], i + "");
}
}
for(Philosopher p : phis) {
p.start();
}
}
}