java 多线程死锁
死锁案例:
package com.test; public class DealThread implements Runnable { public String username; public Object lock1 = new Object(); public Object lock2 = new Object(); public void setFlag(String username) { this.username = username; } @Override public void run() { if (username.equals("a")) { synchronized (lock1) { try { System.out.println("username = " + username); Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); } synchronized (lock2) { System.out.println("按 lock1 -> lock2 代码顺序执行了"); } } } if (username.equals("b")) { synchronized (lock2) { try { System.out.println("username = " + username); Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); } synchronized (lock1) { System.out.println("按 lock2 -> lock1 代码顺序执行了"); } } } } }
package com.test; public class Run { public static void main(String[] args) { try { DealThread d1 = new DealThread(); d1.setFlag("a"); Thread thread1 = new Thread(d1); thread1.start(); Thread.sleep(100); d1.setFlag("b"); Thread thread2 = new Thread(d1); thread2.start(); } catch (Exception e) { e.printStackTrace(); } } }
运行结果: username = a username = b
死锁是程序设计的Bug,在设计程序时就要避免双方互相持有对方锁的情况。本案例使用synchronized嵌套的代码结构来实现死锁,其实不适用嵌套的代码结构也会出现死锁。 只要互相等待对方释放锁就有可能出现死锁。