哲学家吃饭的问题,死循环
import java.util.Random;
public class DiningPhils
{
public static void main(String[] args)
{
int n = 10;
if( n < 1)
{
System.out.println( "DiningPils <# of philosophers>" );
System.exit(-1);
}
DiningPhils self = new DiningPhils();
self.init(n);
}
public int getCount()
{
return n;
}
public void setChopstick( int i, boolean v)
{
chops[ i ] = v;
}
public boolean getChopstick( int i )
{
return chops[i];
}
private void init( final int N)
{
r = new Random();
n = ( N < 0 || N > maxPhils ) ? maxPhils : N;
chops = new boolean[n];
phils = new Philosopher[n];
initPhils();
dumpStatus();
}
private void initPhils()
{
for( int i = 0; i< n; i++ )
{
phils[i] = new Philosopher( this, i );
phils[i].setTimeSlice( generateTimeSlice());
phils[i].setPriority( Thread.NORM_PRIORITY - 1);
/**哲学家进程降低一级,使所有哲学家进程
*全部初始化完毕前不会有哲学家进程抢占主线程*/
}
while( moreToStart() )
{
int i = Math.abs( r.nextInt()) % n;
if( !phils[i].isAlive())
{
System.out.println( " ### Philosopher " +
String.valueOf( i ) + " started.");
phils[i].start();
}
}
System.out.println( "\nPhilosophers Chopsticks"
+ "\n(1 = eating, 0 = thinking) (1 = taken, 0 = free)");
}
public int generateTimeSlice()
{
int ts = Math.abs(r.nextInt()) % (maxEat + 1);
if( ts == 0 )
ts = minEat;
return ts;
}
public void dumpStatus()
{
for( int i = 0; i < n; i++)
System.out.print(phils[i].getEat() ? 1 : 0);
for( int i = n; i < maxPhils + 4; i++ )
System.out.print(" ");
for( int i = 0; i < n; i++)
System.out.print(chops[i]? 1:0);
System.out.println();
}
private boolean moreToStart()
{
for( int i = 0; i < phils.length; i++ )
{