package com.shenzhen.dai;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Philosopher extends Thread {
@Data
@AllArgsConstructor
static class Chopstick {
private int id;
}
private String name;
private Chopstick left, right;
private Random random;
Philosopher(String name, Chopstick left, Chopstick right) {
this.name = name;
this.left = left;
this.right = right;
random = new Random();
}
private void doAction(String action, Integer seconds) throws InterruptedException {
System.out.println(
Thread.currentThread().getName() + " " + action);
Thread.sleep(((int) (Math.random() * 10 * seconds)));
}
@Override
public void run() {
try {
while (true) {
synchronized (left) {
doAction("pick left c", 1);
synchronized (right) {
doAction("pick right c and eating", 1);
doAction("pick down right c", 1);
}
doAction("pick down left c", 1);
}
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws InterruptedException {
List<Philosopher> philosopherList = new ArrayList<>();
List<Object> forks = new ArrayList<>();
for (int i = 0; i < 5; i++) {
forks.add(new Chopstick(i + 1));
}
for (int i = 0; i < forks.size(); i++) {
Chopstick left = (Chopstick) forks.get(i);
Chopstick right = (Chopstick) forks.get((i + 1) % forks.size());
Philosopher philosopher = null;
if (System.identityHashCode(left) < System.identityHashCode(right)) {
philosopher = new Philosopher(("name" + i + 1), left, right);
} else {
philosopher = new Philosopher(("name" + i + 1), right, left);
}
philosopherList.add(philosopher);
}
for (Philosopher philosopher : philosopherList) {
philosopher.start();
System.out.println("System.identityHashCode(philosopher) = " + System.identityHashCode(philosopher));
}
}
}
标签:就餐,right,哲学家,Chopstick,philosopher,System,问题,new,left
From: https://www.cnblogs.com/alvisClub/p/17872094.html