多线程学习笔记三 - 多线程死锁
多线程死锁:
死锁的常见情形之一:同步的嵌套。
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();
}
在我后面的笔记五中,还有对另外一种死锁的形式的介绍,并且介绍了JDK1.5对synchronized同步锁的替代-->Lock接口,虽然出现了替代,但是因为synchronized
同步锁和同步函数的简单性,并且它也能解决工作中的大部分死锁情况,所以synchronized同步锁的应用还是非常的广泛。