[关闭]
@Yano 2016-03-22T09:43:52.000000Z 字数 1072 阅读 2072

Java 代码模拟死锁

面试题


题目描述

Java代码模拟死锁

死锁条件

思路

代码

  1. public class DeadLock implements Runnable {
  2. // flag=1,占有对象o1,等待对象o2
  3. // flag=0,占有对象o2,等待对象o1
  4. public int flag = 1;
  5. // 定义两个Object对象,模拟两个线程占有的资源
  6. public static Object o1 = new Object();
  7. public static Object o2 = new Object();
  8. public static void main(String[] args) {
  9. DeadLock deadLock1 = new DeadLock();
  10. DeadLock deadLock2 = new DeadLock();
  11. deadLock1.flag = 0;
  12. deadLock2.flag = 1;
  13. Thread thread1 = new Thread(deadLock1);
  14. Thread thread2 = new Thread(deadLock2);
  15. thread1.start();
  16. thread2.start();
  17. }
  18. public void run() {
  19. System.out.println("flag: " + flag);
  20. // deadLock2占用资源o1,准备获取资源o2
  21. if (flag == 1) {
  22. synchronized (o1) {
  23. try {
  24. Thread.sleep(1000);
  25. } catch (InterruptedException e) {
  26. e.printStackTrace();
  27. }
  28. synchronized (o2) {
  29. System.out.println("1");
  30. }
  31. }
  32. }
  33. // deadLock1占用资源o2,准备获取资源o1
  34. else if (flag == 0) {
  35. synchronized (o2) {
  36. try {
  37. Thread.sleep(1000);
  38. } catch (InterruptedException e) {
  39. e.printStackTrace();
  40. }
  41. synchronized (o1) {
  42. System.out.println("0");
  43. }
  44. }
  45. }
  46. }
  47. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注