public Diner()
 {
     id = instanceCount++;
     left = DiningPhilosphers.forks[id];
     right = DiningPhilosphers.forks[(id + 1) % DiningPhilosphers.dinerCount];
     state = DinerState.Get;
     Thread thread = new Thread(new ThreadStart(doStuff));
     thread.Start();             // start instance's thread to doStuff()
 }
        public void doStuff()
        {
            do
            {
                if (state == DinerState.Get)
                {
                    bool lockedL = false;
                    Monitor.TryEnter(left, ref lockedL);      //     try lock L

                    if (lockedL)                              //  got left fork
                    {
                        left.holder = id;           //  left fork holder = this
                        bool lockedR = false;
                        Monitor.TryEnter(right, ref lockedR);     // try lock R

                        if (lockedR)                //    lock R succeeded too.
                        {                           //           got both forks
                            right.holder = id;      //      list this as holder
                            state = DinerState.Eat; //                     Eat.
                            Thread.Sleep(DiningPhilosphers.rand.Next(maxWaitMs));
                            right.holder = -1;      // no right fork holder now
                            Monitor.Exit(right);    //                 unlock R
                            left.holder = -1;       //  no left fork holder now
                            Monitor.Exit(left);     //                 unlock L
                            state = DinerState.Pon; //                  Ponder.
                            Thread.Sleep(DiningPhilosphers.rand.Next(maxWaitMs));
                        }
                        else       // got left, but not right, so put left down
                        {
                            left.holder = -1;       //            no holder now
                            System.Threading.Monitor.Exit(left);    // unlock L
                            Thread.Sleep(DiningPhilosphers.rand.Next(maxWaitMs));
                        }
                    }
                    else           //                 could not get either fork
                    {              //                                wait a bit
                        Thread.Sleep(DiningPhilosphers.rand.Next(maxWaitMs));
                    }
                }
                else               //                   state == DinerState.Pon
                {                  //      done pondering, go back to get forks
                    state = DinerState.Get;         //      trying to get forks
                }
            } while (!end);
        }