package philo;

public class Philo extends Thread {
    static final int NUM_PHIL = 5;
    static final int MAX_EAT = 4;
    int id;
    Table t;

public   Philo(int id, Table t) {
        this.id = id;
        this.t = t;
    }

    public void run() {
       System.out.println(id + " run start");
        try {
            int max_eat = 0;
            while (max_eat <  MAX_EAT) {
//                System.out.println(id + " let's try to get the forks"); // eat
                max_eat = t.getForks(id);
//                System.out.println(id + " have the forks now"); // eat
                //long l = (int)(Math.random() * 500) + 20;
//                System.gc();
                //System.out.println(id + " eating (" + l + ")"); // eat
                //sleep(l);
                System.out.println(id + " that was good"); // eat
                t.putForks(id);
            }
        } catch(InterruptedException e) {
            System.out.println(id + " run interrupted");;
        }
        System.out.println(id + " run end");
    }

    public static void main(String args[]) throws Exception {
        Table tab = new Table();
        Philo[] p = new Philo[NUM_PHIL];
        for (int i=0; i < NUM_PHIL; ++i) {
            p[i] = new Philo(i, tab);
            p[i].start();
        }
        for (int i=0; i < NUM_PHIL; ++i)
            p[i].join();
        System.out.println("All Done");
        // main should terminate last to have the access ctr correctly.
    }
}







