Verfügbare Informationen zu "Reisesser"
Qualität des Beitrags: Beteiligte Poster: alexander - Belafarinrod Forum: A-Welt Forum Forenbeschreibung: Das geile Forum aus dem Unterforum: Java-Forum Antworten: 2 Forum gestartet am: Freitag 04.03.2005 Sprache: deutsch Link zum Originaltopic: Reisesser Letzte Antwort: vor 18 Jahren, 5 Monaten, 5 Tagen, 4 Stunden, 48 Minuten
Alle Beiträge und Antworten zu "Reisesser"
Re: Reisesser
alexander - 16.11.2005, 18:44Reisesser
Damit ihr und ich nicht in der Schule den ganzen Kramm abtimmern braucht:
Code: // Autor: Alex
// Datum: 16.11.2005
class PhilosopherManager
{
public final static int N = 5;
private static int[] phils;
private final static int THINKING = 0, HUNGRY = 1, EATING = 2;
static
{
phils = new int[N];
for(int i=0; i<N; i++)
phils[i] = THINKING;
}
private int left(int i){ return (i+N-1)%N; }
private int right(int i){ return (i+1)%N; }
synchronized public void takeForks(int no)
{
while(phils[left(no)]==EATING || phils[right(no)]==EATING)
{
try{
wait();
} catch (InterruptedException e){ }
}
phils[no] = EATING;
display(EATING);
}
synchronized public void putForks(int no)
{
phils[no] = THINKING;
display(THINKING);
notifyAll();
}
synchronized public void setHungry(int no)
{
phils[no] = HUNGRY;
display(HUNGRY);
}
synchronized public void display(int zustand)
{
String s;
if(zustand==THINKING) s = "Think. Philosophers : ";
else if(zustand==HUNGRY) s = "Hungry Philosophers : ";
else s = "Eating Philosophers : ";
for(int i=0; i<N; i++)
if(phils[i] == zustand)
s = s+" "+i;
System.out.println(s);
}
} // End of PhilosopherManager-Class
public class Philosopher extends Thread
{
int no;
PhilosopherManager m;
public Philosopher(int no, PhilosopherManager m)
{
super("Phil. "+no);
this.no = no;
this.m = m;
}
void eat()
{
try{
sleep(500+(int)(Math.random()/50-25));
} catch (InterruptedException e) { }
}
void think()
{
try{
sleep(1000+(int)(Math.random()/50-50));
} catch (InterruptedException e) { }
}
public void run()
{
for(int j=0; j<5; j++)
{
think();
m.setHungry(no);
m.takeForks(no);
eat();
m.putForks(no);
}
}
public static void main(String[] args) {
PhilosopherManager m = new PhilosopherManager();
Philosopher[] p = new Philosopher[PhilosopherManager.N];
for(int i=0; i<p.length; i++)
p[i] = new Philosopher(i, m);
for(int i=0; i<p.length; i++)
p[i].start();
for(int i=0; i<p.length; i++)
{
try{
p[i].join();
} catch(Exception e){
System.out.println(e);
}
}
}
} // End of Philosopher-Class
Re: Reisesser
Belafarinrod - 23.11.2005, 23:10
Oh man, dass glaubt der mir nie das es von mir ist. isch lass es lieber. aber trotzdem danke.
Belafarinrod
Mit folgendem Code, können Sie den Beitrag ganz bequem auf ihrer Homepage verlinken
Weitere Beiträge aus dem Forum A-Welt Forum
A-Welt Forum ist Nr 1!!! - gepostet von alexander am Sonntag 05.03.2006
Ähnliche Beiträge wie "Reisesser"