-
- 死锁——两个线程都在等待对方先完成,造成程序的停滞
- 死锁的条件:
- 两个或两个以上的线程在活动
- 某个线程拿到一个锁以后,还想拿第二个锁,造成锁的嵌套
public class Test { public static void main(String[] args) { Object bobby = new Object(); Object duck = new Object(); Thread tangtang = new Thread(new TangTang(bobby,duck)); Thread doudou = new Thread(new DouDou(bobby,duck)); tangtang.start(); doudou.start(); } } class TangTang implements Runnable{ Object bobby ; Object duck ; public TangTang(Object bobby, Object duck) { super(); this.bobby = bobby; this.duck = duck; } @Override public void run() { synchronized(bobby){ try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized(duck){ } } System.out.println("芭比给你玩!"); } } class DouDou implements Runnable{ Object bobby ; Object duck ; public DouDou(Object bobby, Object duck) { super(); this.bobby = bobby; this.duck = duck; } @Override public void run() { synchronized(duck){ try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized(bobby){ } } System.out.println("玩具鸭给你玩!"); } }
死锁产生的原因
最新推荐文章于 2024-08-04 14:57:14 发布