⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 deadlock.java

📁 多线程 课堂讲解代码 很经典的
💻 JAVA
字号:
import java.util.Timer;
import java.util.TimerTask;

//声明Fork类
class Fork {
  private static int counter = 0;
  private int number = counter++;
  public String toString() {
    return "" + number +" 的叉子";
  }
} // 类Fork结束

//声明Philosopher类
class Philosopher extends Thread {
  private int number = 0;
  private Fork leftFork;
  private Fork rightFork;

  public Philosopher(int number, Fork left, Fork right) {
    this.number = number;
    leftFork = left;
    rightFork = right;
  }

  public void thinking() {
    System.out.println(this +" 在思考");
    try {
      sleep( (int) (Math.random() * 100));
    } catch (InterruptedException e) {
      System.out.println("Exception: " + e.getMessage());
    } 
  } // think方法结束

  public void eating() {
    synchronized (leftFork) {
      System.out.println(this + " 拥有编号为 " + this.leftFork
                          + " 正在等待编号为 " + this.rightFork);
       try {
         sleep( (int) (Math.random() * 50));
       } catch (InterruptedException e) {
         System.out.println("Exception: " + e.getMessage());
       } 
      synchronized (rightFork) {
        System.out.println("哲学家 " + number + " 现在拥有两把叉子");
        System.out.println(this + " 正在吃面条");      }
    }
  } // eat方法结束

  public String toString() {
    return "哲学家 " + number;
  }

  public void run() {
    while (true) {
      thinking();
      eating();
    }
  } // run方法结束
} // 类Philosopher结束

class Timeout extends Timer {
  public Timeout(int delay, final String msg) {
    super(true);
    schedule(new TimerTask() {
      public void run() {
        System.out.println(msg);
        System.exit(0);
      } // run方法结束
    }, delay);
  }
} // 类Timeout结束

//声明主测试类
public class Deadlock {
  private static int DELAYTIME = 20;  //死锁发生时,系统退出延时时间
  public static void main(String[] args) {
    Fork left = new Fork();
    Fork right = new Fork(); 
    Philosopher philosopher1 = new Philosopher(1,left,right);
    Philosopher philosopher2 = new Philosopher(2,right,left);
    philosopher1.start();
    philosopher2.start();
    new Timeout(DELAYTIME * 1000, "死锁超时,程序退出");
  } // main方法结束
} // 类Deadlock结束

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -