Skip to content

Instantly share code, notes, and snippets.

@ichistmeinname
Created April 23, 2014 13:27
Show Gist options
  • Save ichistmeinname/e8221ec35a7eb9530921 to your computer and use it in GitHub Desktop.
Save ichistmeinname/e8221ec35a7eb9530921 to your computer and use it in GitHub Desktop.
public class SyncPhilosopher implements Runnable {
private Object left;
private Object right;
private int num;
public SyncPhilosopher(int num, Object left, Object right) {
this.left = left;
this.right = right;
this.num = num;
}
public synchronized void test() {
// irgendwas nebenlaeufiges
}
// ist das gleiche wie
// public void test() {
// // sehr ressourcenlastige Berechnung
// synchronized(this) {
// irgendwas nebenlaeufiges
// }
// }
public void run() {
// sehr naive Loesung
while (true) {
// thinking
System.out.println(num + " thinking");
// eating
synchronized(left) {
synchronized(right) {
try {
Thread.sleep((long) 1000*Math.random());
} catch (InterruptedException e) {
}
System.out.println(num + " eating");
} // Lock "right" wieder frei
} // Lock "left" wieder frei
}
}
public static void main(String[] args) {
int count = 4;
if (args.length > 0) {
try {
count = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
}
}
Object sticks[] = new Object[count];
SyncPhilosopher phils[] = new SyncPhilosopher[count];
//
for (int i=0; i<count; i++) {
sticks[i] = new Object();
}
for (int i=0; i<count-1; i++) {
phils[i] = new SyncPhilosopher(i,sticks[i],sticks[(i+1) % count]);
new Thread(phils[i]).start();
// bei `extends Thread`:
// phils[i].start()
}
phils[3] = new SyncPhilosopher(3,sticks[0],sticks[3]);
new Thread(phils[3]).start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment