62,636
社区成员




- public synchronized void setStatus(boolean status){
- dirty = status;
- }
- public synchronized boolean getStatus(){
- return this.dirty;
- }
- public synchronized void setOwner(int owner){
- this.owner = owner;
- }
- public synchronized int getOwner(){
- return owner;
- }
- Stick leftStick, rightStick;
- Philo leftPhilo, rightPhilo;
- int number, eatTimes;
- DinningPhi dinningExam;
- Thread t;
- public boolean answer(Stick used){
- boolean retFlag = false;
- synchronized(this){
- if(used.getStatus()){
- if(used == leftStick)
- used.setOwner(leftPhilo.number);
- else if(used == rightStick)
- used.setOwner(rightPhilo.number);
- else{
- System.out.println("Error status!");
- retFlag = false;
- }
- used.setStatus(false);
- retFlag = true;
- }
- else
- retFlag = false;
- }
- if(retFlag)
- dinningExam.repaint();
- return retFlag;
- }
- public void eating(){
- try{
- Thread.sleep(3000);
- }catch(InterruptedException ie){
- System.out.println("Catch an Interrupted Exception!");
- return;
- }
- leftStick.setStatus(true);
- rightStick.setStatus(true);
- eatTimes++;
- dinningExam.repaint();
- return;
- }
- public void run(){
- Random r = new Random();
- int intR;
-
- while(true){
- while(leftStick.getOwner() != number | rightStick.getOwner() != number){
- intR = r.nextInt();
- if(intR % 2 == 0 & leftStick.getOwner() != number)
- leftPhilo.answer(leftStick);
- else if(intR % 2 == 1 & rightStick.getOwner() != number)
- rightPhilo.answer(rightStick);
- }
- synchronized(this){
- if(leftStick.getOwner() == number
- & rightStick.getOwner() == number){
- eating();
- }
- }
- try{
- int sleepSec = r.nextInt();
- if(sleepSec < 0)
- sleepSec = -sleepSec;
- Thread.sleep(sleepSec % 500);
- }catch(InterruptedException ie){
- System.out.println("Catch an Interrupted Exception!");
- }
- }
- }