80 lines
2.0 KiB
Java
80 lines
2.0 KiB
Java
package PhilosophenPak;
|
|
|
|
import java.util.ArrayList;
|
|
|
|
public class PhilosophenAIO {
|
|
public static void main(String[] args) {
|
|
//int n =Integer.parseInt(args[0]);
|
|
int n = 5;
|
|
var pList = new ArrayList<Thread>();
|
|
var gList= new ArrayList<Gabel>();
|
|
for(int it =0;it<n;it++){
|
|
Gabel g=new Gabel(it);
|
|
gList.add(g);
|
|
}
|
|
for(int i=0;i<n;i++){
|
|
Gabel left = gList.get(i);
|
|
Gabel right;
|
|
if (i==0){
|
|
right = gList.get(gList.size()-1);
|
|
}else {
|
|
right = gList.get(i-1);
|
|
}
|
|
Thread t = new Philosoph("Philosoph "+i,left, right);
|
|
pList.add(t);
|
|
t.start();
|
|
}
|
|
}
|
|
}
|
|
|
|
class Philosoph extends Thread {
|
|
String name;
|
|
Gabel left,right;
|
|
public Philosoph(String pname,Gabel pleft, Gabel pright){
|
|
name=pname;
|
|
left=pleft;
|
|
right=pright;
|
|
}
|
|
|
|
@Override
|
|
public void run() {
|
|
while (true){
|
|
try {
|
|
Thread.sleep(500);
|
|
}catch (Exception e){
|
|
e.printStackTrace();
|
|
}
|
|
if(right.take(name)){
|
|
if(left.take(name)){
|
|
System.out.println(name+" " +"Yeeting");
|
|
right.place(name);
|
|
left.place(name);
|
|
}else{
|
|
right.place(name);
|
|
System.out.println(name+" hat kein links");
|
|
}
|
|
}else {
|
|
System.out.println(name+" hat kein rechts");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
class Gabel {
|
|
public boolean takable =true;
|
|
int id;
|
|
public Gabel(int pID){
|
|
id=pID;
|
|
}
|
|
public synchronized boolean take(String name) {
|
|
if(!takable)
|
|
return false;
|
|
System.out.println(name+" hat Gabel "+id+" genommen");
|
|
takable=false;
|
|
return true;
|
|
}
|
|
public synchronized void place(String name){
|
|
System.out.println(name+" hat Gabel "+id+" zuruckgelegt");
|
|
takable = true;
|
|
}
|
|
} |