Problem Description:
There are 5 philosophers, sharing a table with 5 chairs, each with a chair, but there are 5 chopsticks on the table, one on each side, and the philosophers try to pick up the chopsticks from both sides at two times when they are hungry. Condition: 1) When you get two chopsticks, the philosopher begins to eat. 2) If the chopsticks are already in the hands of others, the philosopher must wait for others to finish eating before they can get the chopsticks. 3) Any philosopher who does not put down his chopsticks in his hand before he gets two chopsticks.
Problem Solving Ideas:
If 2 chopsticks are not used by philosophers, philosophers can dine, and philosophers will only wait for others to finish their meals. Then according to the philosopher's side of the chopsticks state to make judgments, meet the conditions of eating, not satisfied is waiting
Code:
1 Public classPhilosophertest {2 Public Static voidMain (String args[]) {3Philosopher PL =Newphilosopher1 ();4Thread Thread1 =NewThread (PL, "1");5Thread thread2 =NewThread (PL, "2");6Thread thread3 =NewThread (PL, "3");7Thread thread4 =NewThread (PL, "4");8Thread THREAD5 =NewThread (PL, "5");9 Thread1.start ();Ten Thread2.start (); One Thread3.start (); A Thread4.start (); - Thread5.start (); - } the - } - - classPhilosopherImplementsrunnable{ + Private Static Boolean[] Fork = {false,false,false,false,false}; - + @Override A Public voidrun () { at while(true) { - eating (); - thinking (); - } - } - in Public synchronized voideating () { - Try{ to inti =Integer.parseint (Thread.CurrentThread (). GetName ()); + if(fork[i% 5] = =false&& Fork[i-1] = =false){ -Thread.Sleep (500);//simulating the eating process theSystem.out.println ("At the moment of eating is" +Thread.CurrentThread (). GetName ()); *Fork[i% 5] =true; $FORK[I-1] =true;Panax Notoginseng}Else{ - wait (); the } +}Catch(Exception e) { A e.printstacktrace (); the } + } - $ Public synchronized voidthinking () { $ Try{ - inti =Integer.parseint (Thread.CurrentThread (). GetName ()); - if(fork[i% 5] = =true&& Fork[i-1] = =true) { theThread.Sleep (500);//Simulation Thinking Process -System.out.println (Thread.CurrentThread (). GetName () + "already eaten.");WuyiFork[i% 5] =false; theFORK[I-1] =false; - Notifyall (); Wu } -}Catch(Exception e) { About e.printstacktrace (); $ } - - } -}
Thread Learning Five: The problem of dining philosophers