用餐哲学家算法死锁

时间:2014-10-30 07:14:26

标签: java multithreading

我已经编写了解决餐饮哲学家问题的算法。但它给予stackoverflow异常。任何人都可以帮助我。解决一些问题。这是使用多线程的餐饮哲学家问题。我在哪里用ArrayList来存放筷子和盘子。

`      -----------

package com.intech.DiningPhilosopherProblem;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.annotation.processing.Processor;

public class MyPhilosophers {

/**
 * @param args
 */

static int noOfP = ((Runtime.getRuntime().availableProcessors() * 2) + (1)); 
     // Runtime.getRuntime().availableProcessors();

public static void main(String[] args) throws InterruptedException {
    MyPhilosophersChopstick myPs = new MyPhilosophersChopstick(noOfP);
    ExecutorService execserv = Executors.newFixedThreadPool(5);
    for (int i = 0; i < 500; i++) {
        Thread.sleep(200);
        execserv.execute(myPs);
    }

    // execserv.shutdown(); // Disable new tasks from being submitted
    try {
        // Wait a while for existing tasks to terminate
        if (!execserv.awaitTermination(600, TimeUnit.SECONDS)) {
            execserv.shutdownNow(); // Cancel currently executing tasks
            // Wait a while for tasks to respond to being cancelled
            if (!execserv.awaitTermination(600, TimeUnit.SECONDS))
                System.err.println("Pool did not terminate");
        }
    }

    catch (InterruptedException ie) {
        // (Re-)Cancel if current thread also interrupted
        execserv.shutdownNow();
        // Preserve interrupt status
        Thread.currentThread().interrupt();
    }

}

}

`


    package com.intech.DiningPhilosopherProblem;

     public class MyPhilosophersChopstick implements Runnable {

volatile int eatingturns =0;
volatile int allowedeatingturns =200;
volatile int noOfChopsticks=0;
volatile int[] arrayChopsticks;
volatile int i=0;


public MyPhilosophersChopstick(int chopsticks)
{
    arrayChopsticks=new int[chopsticks];
    this.noOfChopsticks=chopsticks;
    for (int i = 0; i < noOfChopsticks; i++) 
    {
        arrayChopsticks[i]=0;
    }
    System.out.println("noOfChopsticks"+noOfChopsticks);
    System.out.println("arrayChopsticks.length"+arrayChopsticks.length);
}

public void run() 
{   System.out.println("run count"+ i++);

    while(eatingturns<allowedeatingturns)
    {   



    String s=Thread.currentThread().getName();
    char c=s.charAt(s.length()-1);   //c = which thread thread no 1, thread no 2, thread no 3, thread no 4. It denotes to which philosopher in char

    int j=(int)c;                    //j = which thread thread no 1, thread no 2, thread no 3, thread no 4. It denotes to which philosopher in int where 0=49 , 1=50....  and so on
    System.out.println("j"+j);
    if(c>noOfChopsticks)
        System.out.println("c"+c);
    j=j-49;                          //converting char in to int digits as value for 0=49, 1=50....  and so on
    System.out.println("j"+j);
    System.out.println( Thread.currentThread().getName()+"Thinking-------------"+j);

    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    hungary(j);
    }
}


public void hungary(int i)
{
    //System.out.println( Thread.currentThread().getName()+"Inside hungary()-------------"+i);
      //else nothing

    boolean a=eat(i);
    if(a==true)
        System.out.println(Thread.currentThread().getName()+"Eating-------------"+i+""+arrayChopsticks[i]);
    synchronized (this){
        eatingturns++;
    }

    a=doneEating(i);


}

private boolean eat(int i) {
    // TODO Auto-generated method stub
    // System.out.println(
    // Thread.currentThread().getName()+"Inside eat()-------------"+i);
    boolean a;
    boolean b;

    if (i == 0) {
        synchronized (this) {
            if ((a = pickchopstickRight(i))
                    && (b = pickchopstickLeft(arrayChopsticks.length - 1))) {
                return true;
            }
            keepChopstickRight(i); // if right chopstick not available

            return false;

        }
    } else {
        if ((a = pickchopstickRight(i)) && (b = pickchopstickLeft(i - 1))) {
            return true;
        }
        keepChopstickRight(i); // if right chopstick not available

        return false;
    }

}
private boolean doneEating(int i) {
    // TODO Auto-generated method stub
    //System.out.println( Thread.currentThread().getName()+"Inside wantToThink()-------------"+i);
    boolean a;
    boolean b;

    if(i==0){
    //synchronized (this)
    {

    a=keepChopstickLeft(arrayChopsticks.length-1);  
    b=keepChopstickRight(i);
    }
    }
    else
    {
        a=keepChopstickLeft(i-1);
        b=keepChopstickRight(i);    //pandey
    }



    if(a&&b)
    {
        return true;
    }
    return false;       
}





private boolean keepChopstickLeft(int i) {

    //System.out.println( Thread.currentThread().getName()+"INSIDE keepchopstick Left -------------"+i);

    if(arrayChopsticks[i]==1)
    {
        System.out.println( Thread.currentThread().getName()+"Keeping down Left chopstick -------------"+i+""+arrayChopsticks[i]);
        arrayChopsticks[i]=0;
        return true;
    }
    return false;

}


private boolean keepChopstickRight(int i) 
{
    System.out.println( Thread.currentThread().getName()+"INSIDE keepchopstick Right -------------"+i+""+arrayChopsticks[i]);

    if(arrayChopsticks[i]==1)
    {
        System.out.println( Thread.currentThread().getName()+"Keeping down Right chopstick -------------"+i+""+arrayChopsticks[i]);
        arrayChopsticks[i]=0;
        run();   //goest to run
    }

    return false;
}


private boolean pickchopstickLeft(int i) 
{
    //System.out.println( Thread.currentThread().getName()+"INSIDE pickchopstickLEFT -------------"+i);

    if(arrayChopsticks[i]==0)
    {
        System.out.println( Thread.currentThread().getName()+"picking up chopstick Left -------------"+i+""+arrayChopsticks[i]);
        arrayChopsticks[i]=1;
        return true;
    }
    return false;

}


private boolean pickchopstickRight(int i) {


    //System.out.println( Thread.currentThread().getName()+"INSIDE pickchopstickRight -------------"+i);

    if(arrayChopsticks[i]==0)
    {

        System.out.println( Thread.currentThread().getName()+"picking up chopstick Right -------------"+i+""+arrayChopsticks[i]);
        arrayChopsticks[i]=1;
        return true;
    }
    return false;

}

}

1 个答案:

答案 0 :(得分:1)

可能是程序中存在内存泄漏,或者您必须使用-xMx -Xms来增加堆和堆栈大小