1. ![image.png](https://cdn.nlark.com/yuque/0/2022/png/23190196/1644230624022-b2578919-36b2-4e88-b049-cda8264ba885.png#clientId=ubba200b5-a4a3-4&from=paste&height=313&id=u87297ec6&margin=%5Bobject%20Object%5D&name=image.png&originHeight=574&originWidth=653&originalType=binary&ratio=1&size=133062&status=done&style=none&taskId=u6e762ae7-62a6-4dc2-a47f-0a6246e59b3&width=356.4957580566406)<br />有五位哲学家,围坐在圆桌旁。
    • 他们只做两件事,思考和吃饭,思考一会吃口饭,吃完饭接着思考
    • 吃饭时要用两根筷子吃,桌上一共有5根筷子,每位哲学家左右手边各有一根筷子。
    • 如果筷子被身边的人拿着,自己就得等待

    哲学家模拟代码如下:
    其中哲学家创建为线程类,筷子可以视为加锁的资源。
    筷子对象在哲学家对象构造时会将其传入,所以可以保证多个线程能够共享筷子对象,从而实现互斥(锁住的是同样的筷子)

    1. public class TestDeadLock {
    2. public static void main(String[] args) {
    3. //创建五根筷子
    4. Chopstick c1 = new Chopstick("1");
    5. Chopstick c2 = new Chopstick("2");
    6. Chopstick c3 = new Chopstick("3");
    7. Chopstick c4 = new Chopstick("4");
    8. Chopstick c5 = new Chopstick("5");
    9. new Philosopher("苏格拉底",c1,c2).start();
    10. new Philosopher("柏拉图",c2,c3).start();
    11. new Philosopher("亚里士多德",c3,c4).start();
    12. new Philosopher("赫拉克利特",c4,c5).start();
    13. new Philosopher("阿基米德",c5,c1).start();
    14. }
    15. }
    16. class Philosopher extends Thread{
    17. //两双筷子
    18. Chopstick left;
    19. Chopstick right;
    20. /*注意这里的筷子对象,在构造时要传入,所以可以保证下边synchronized锁住的是同一个对象*/
    21. public Philosopher(String name,Chopstick left,Chopstick right){
    22. //name传给上层方法
    23. super(name);
    24. this.left=left;
    25. this.right=right;
    26. }
    27. @Override
    28. public void run() {
    29. while (true){//不是吃饭就是睡觉,所以要加while
    30. //尝试获取左筷子
    31. synchronized (left){
    32. //尝试获取右筷子
    33. synchronized (right){
    34. try {
    35. System.out.println(super.getName());
    36. eat();//左右筷子都获得,开始吃饭
    37. } catch (InterruptedException e) {
    38. e.printStackTrace();
    39. }
    40. }
    41. }
    42. }
    43. }
    44. private static void eat() throws InterruptedException {
    45. System.out.println("eating...");
    46. Thread.sleep(1000);
    47. }
    48. }
    49. class Chopstick{
    50. String name;
    51. public Chopstick(String name){this.name=name;}
    52. @Override
    53. public String toString() {
    54. return super.toString();
    55. }
    56. }

    运行一段时间后,会出现死锁现象,每位哲学家各拿一根筷子,同时去争抢其它筷子。