public class DeadlockDemo implements Runnable { //首先定义两个死锁对象 //public int flag =1; public static Object o1 = new Object(); public static Object o2 = new Object(); //定义属性又叫成员变量 public int flag; public DeadlockDemo(int flag) { //super(); this.flag = flag; } @Override public void run() { if (flag == 1){ synchronized (o1) { System.out.println("筷子"); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (o2) { System.out.println("叉子"); } } }else { synchronized (o2){ System.out.println("叉子"); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (o1){ System.out.println("筷子"); } } } } public static void main(String[] args){ DeadlockDemo deadlockDemo1 = new DeadlockDemo(1); DeadlockDemo deadlockDemo2 = new DeadlockDemo(2); new Thread(deadlockDemo1).start(); new Thread(deadlockDemo2).start(); } }
06-19
1659
12-07