标签:size [] art 线程 obj stack col public 顺序
死锁问题;
public class DeadLock { //锁的嵌套 会出现死锁 //1 尽量不要去写锁嵌套 //2 private static Object locka = new Object(); private static Object lockb = new Object(); public static void main(String[] args) { new DeadLock().deadLock(); } private void deadLock() { Thread thread1 = new Thread(new Runnable() { @Override public void run() { synchronized (locka){ try { System.out.println(Thread.currentThread().getName()+"获取A锁 ing~!"); Thread.sleep(500); System.out.println(Thread.currentThread().getName()+"睡眠 500ms!"); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"需要B锁!!!"); synchronized (lockb){ System.out.println(Thread.currentThread().getName()+"B锁中!!!"); } } } },"thread1"); Thread thread2 = new Thread(new Runnable() { @Override public void run() { synchronized (lockb){ try { System.out.println(Thread.currentThread().getName()+"获取B锁 ing~!"); Thread.sleep(500); System.out.println(Thread.currentThread().getName()+"睡眠 400ms!"); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"需要A锁!!"); synchronized (locka){ System.out.println(Thread.currentThread().getName()+"A锁中!"); } } } },"thread2"); thread1.start(); thread2.start(); } }
锁的嵌套 会出现死锁
1 尽量不要去写锁嵌套
2 锁嵌套的顺序
3 引入超时机制
标签:size [] art 线程 obj stack col public 顺序
原文地址:https://www.cnblogs.com/fuckingPangzi/p/10157225.html