多线程死锁:
死锁的常见情形之一:同步的嵌套。
public class DeadLock { public static void main(String[] args) throws InterruptedException { Customer cus = new Customer(); Thread t1 = new Thread(cus); Thread t2 = new Thread(cus); t1.start(); Thread.sleep(5); cus.flag = false; t2.start(); } } class Bank2{ private double sumMoney; public double getSumMoney() { return sumMoney; } public void setSumMoney(double sumMoney) { this.sumMoney = sumMoney; } public void add(double money){ sumMoney += money; System.out.println(Thread.currentThread().getName()+"save:"+money+" Bank2 has "+sumMoney); } } class Customer implements Runnable{ Bank2 b = new Bank2(); public boolean flag = true; Object obj = new Object(); @Override public void run() { if(flag){ while(true){ if(b.getSumMoney() < 100000){ synchronized(obj){ this.Operation(); } }else{break;} } }else{ while(true){ if(b.getSumMoney() < 100000){ this.Operation(); }else{break;} } } } public synchronized void Operation(){ synchronized (obj) { b.add(1000); System.out.println("======function=====");; } } }
运行结果:
======function=====
Thread-1save:1000.0 Bank2 has 34000.0
======function=====
Thread-1save:1000.0 Bank2 has 35000.0
======function=====
Thread-1save:1000.0 Bank2 has 36000.0
======function=====
Thread-1save:1000.0 Bank2 has 37000.0
======function=====
Thread-1save:1000.0 Bank2 has 38000.0
======function=====
到38000时候发生了死锁。
死锁小实例:(面试时候用)
public class DeadLockTest { public static void main(String[] args) throws InterruptedException { MyThread mt1 = new MyThread(); Thread t1 = new Thread(mt1); Thread t2 = new Thread(mt1); t1.start(); Thread.sleep(1); mt1.flag = false; t2.start(); } } class MyThread implements Runnable{ public boolean flag = true ; @Override public void run() { while(true){ if(flag){ synchronized(LockObject.obja){ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"if===obja"); synchronized(LockObject.objb){ System.out.println(Thread.currentThread().getName()+"if===objb"); } } }else{ synchronized(LockObject.objb){ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"else===obja"); synchronized(LockObject.obja){ System.out.println(Thread.currentThread().getName()+"else===objb"); } } } } } } class LockObject{ public static final Object obja = new Object(); public static final Object objb = new Object(); }
时间: 2024-11-01 19:39:51