Operation Result:
Java code:
1 Public classMain {2 3 Public Static voidMain (string[] args) {4Global global=NewGlobal ();5 6Philosopher ph[]=NewPhilosopher[5];7 inti;8 for(i=0;i<5;i++){9ph[i]=Newphilosopher (i);Ten } OneThread[] Ph_t=NewThread[5]; A for(i=0;i<5;i++){ -ph_t[i]=NewThread (Ph[i]); - } the for(i=0;i<5;i++){ - Ph_t[i].start (); - } - } + } - + A classsyn{//PV Operation class at intcount=0;//Signal Volume - syn () {} -SynintA) {count=A;} - Public synchronized voidWait () {//The keyword synchronized guarantees that this operation is a "primitive language" -count--; - if(count<0) {//equals 0: A process has entered the critical section in Try{//less than 0:abs (count) = number of blocked processes - This. Wait (); to}Catch(interruptedexception e) { + E.printstacktrace (); - } the } * } $ Public synchronized voidSignal () {//The keyword synchronized guarantees that this operation is a "primitive language"Panax Notoginsengcount++; - if(count<=0) {//If there is a process blocking the This. Notify ();// All + } A } the } + - classglobal{ $ StaticSyn chopsticks[]=NewSyn[5]; $ Static intCount=0; - Global () { - inti; the for(i=0;i<5;i++){ -chopsticks[i]=NewSYN (1);//Initialize the semaphoreWuyi } the } - } Wu - classPhilosopherImplementsrunnable{//Philosopher Class About intId=0; $ philosopher () {} -Philosopher (intID) { -Id=ID; - } A Public voidrun () { + while(true){//global.count<20 the //pick up left chopsticks - Global.chopsticks[id]. Wait (); $global.chopsticks[(id+1)%5]. Wait (); the theglobal.count++; theSystem.out.println ("Philosopher" +id+ "picked up chopsticks" +id+ "and Chopsticks" + ((id+1)%5) + "A good meal"); the Try { -Thread.Sleep (10); in}Catch(interruptedexception e) { the //TODO auto-generated Catch block the e.printstacktrace (); About } the the Global.chopsticks[id]. Signal (); theglobal.chopsticks[(id+1)%5]. Signal (); + } - } the}
Java Implementation PV Operations | The question of the Philosopher's meal