前言
记录学习过程
死锁是多线程并发中容易出现的问题
有很多常见的死锁
目录
概念
在操作系统中学过死锁的概念
死锁:两个或两个以上的线程在执行过程中,由于竞争资源或者由于彼此通信而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去
死锁的发生必须具备以下四个必要条件。
- 互斥条件:指进程对所分配到的资源进行排它性使用,即在一段时间内某资源只由一个进程占用。如果此时还有其它进程请求资源,则请求者只能等待,直至占有资源的进程用毕释放。
- 请求和保持条件:指进程已经保持至少一个资源,但又提出了新的资源请求,而该资源已被其它进程占有,此时请求进程阻塞,但又对自己已获得的其它资源保持不放。
- 不剥夺条件:指进程已获得的资源,在未使用完之前,不能被剥夺,只能在使用完时由自己释放。
- 环路等待条件:指在发生死锁时,必然存在一个进程——资源的环形链,即进程集合{P0,P1,P2,···,Pn}中的P0正在等待一个P1占用的资源;P1正在等待P2占用的资源,……,Pn正在等待已被P0占用的资源。
程序碰到的死锁
锁顺序死锁
package com.company.Thread.Deadlock;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class LeftRightDeadlock implements Runnable{
private volatile boolean choose=true;
private final static Object left = new Object();
private final static Object right = new Object();
public LeftRightDeadlock(boolean choose) {
this.choose = choose;
}
public void leftRight() throws InterruptedException {
// 得到left锁
synchronized (left) {
System.out.println("线程1:获得左锁");
Thread.sleep(1000);
// 得到right锁
synchronized (right) {
System.out.println("线程1:获得右锁");
}
}
}
public void rightLeft() throws InterruptedException {
// 得到right锁
synchronized (right) {
System.out.println("线程2:获得右锁");
Thread.sleep(1000);
// 得到left锁
synchronized (left) {
System.out.println("线程2:获得左锁");
}
}
}
public static void main(String[] args){
//固定线程池
ExecutorService pool=Executors.newFixedThreadPool(2);
//两个线程,一个执行rightLeft,一个执行leftRight
LeftRightDeadlock leftRightDeadlock=new LeftRightDeadlock(true);
LeftRightDeadlock leftRightDeadlock1=new LeftRightDeadlock(false);
pool.submit(leftRightDeadlock);
pool.submit(leftRightDeadlock1);
}
@Override
public void run() {
if(choose) {
try {
leftRight();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else {
try {
rightLeft();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
线程1占有了左锁,在等待右锁
线程2占有了右锁,在等待左锁
这就是最简单的死锁:锁顺序死锁
动态锁顺序死锁
Account类:
package com.company.Thread.Deadlock;
public class Account {
private int count;
public Account(int count) {
this.count = count;
}
public int getCount() {
return count;
}
//账号转账减钱
public void debit(int amount){
this.count=count-amount;
}
//加钱
public void credit(int amount){
this.count=count+amount;
}
}
转账方法:
package com.company.Thread.Deadlock;
public class First implements Runnable{
private static Account fromAccount=new Account(10000);
private static Account toAccount=new Account(3000);
// 转账
public static void transferMoney(Account fromAccount,
Account toAccount,
int amount)
{
// 锁定汇账账户
synchronized (fromAccount) {
// 锁定来账账户
try {
Thread.sleep(1000);
System.out.println("获得账户对象hashCode:"+fromAccount.hashCode());
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (toAccount) {
// 判余额是否大于0
if (fromAccount.getCount()-(amount) < 0) {
System.out.println("余额不足以转账"+amount);
}
else {
// 汇账账户减钱
fromAccount.debit(amount);
System.out.println("转账成功");
int form=fromAccount.getCount();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 来账账户增钱
toAccount.credit(amount);
System.out.println("入账成功");
int to=toAccount.getCount();
System.out.println("转账成功:汇款账户余额:"+form+",来账账户余额:"+to);
}
}
}
}
public static void main(String[] args){
First first=new First();
Thread thread=new Thread(first);
thread.start();
Thread thread1=new Thread(()->transferMoney(toAccount,fromAccount,1000));
thread1.start();
}
@Override
public void run() {
transferMoney(fromAccount,toAccount,1000);
}
}
上面的代码看起来是没有问题的:锁定两个账户来判断余额是否充足才进行转账
线程1:fromAccount往toAccount转账
线程2:toAccount往fromAccount转账
一个获得了fromAccount对象,一个获得了toAccount对象,就死锁了
协作死锁
隐式获取两个锁
public class CooperatingDeadlock {
// Warning: deadlock-prone!
class Taxi {
@GuardedBy("this") private Point location, destination;
private final Dispatcher dispatcher;
public Taxi(Dispatcher dispatcher) {
this.dispatcher = dispatcher;
}
public synchronized Point getLocation() {
return location;
}
// setLocation 需要Taxi内置锁
public synchronized void setLocation(Point location) {
this.location = location;
if (location.equals(destination))
// 调用notifyAvailable()需要Dispatcher内置锁
dispatcher.notifyAvailable(this);
}
public synchronized Point getDestination() {
return destination;
}
public synchronized void setDestination(Point destination) {
this.destination = destination;
}
}
class Dispatcher {
@GuardedBy("this") private final Set<Taxi> taxis;
@GuardedBy("this") private final Set<Taxi> availableTaxis;
public Dispatcher() {
taxis = new HashSet<Taxi>();
availableTaxis = new HashSet<Taxi>();
}
public synchronized void notifyAvailable(Taxi taxi) {
availableTaxis.add(taxi);
}
// 调用getImage()需要Dispatcher内置锁
public synchronized Image getImage() {
Image image = new Image();
for (Taxi t : taxis)
// 调用getLocation()需要Taxi内置锁
image.drawMarker(t.getLocation());
return image;
}
}
class Image {
public void drawMarker(Point p) {
}
}
}
getImage()和setLocation(Point location)都需要两个锁:Taxi、Dispatcher,内部也没有释放锁操作,就容易造成死锁
避免死锁
避免死锁可以概括成三种方法:
-
固定加锁的顺序(针对锁顺序死锁)
设置相同顺序、HashCode设置顺序 -
开放调用(针对对象之间协作造成的死锁)
即避免在持有锁的情况下调用外部的方法 -
使用定时锁–>tryLock()
如果等待获取锁时间超时,则抛出异常而不是一直等待!
固定顺序
- 锁顺序死锁
前面的案例,一个是left - right,一个是 right - left,那设置个相同的顺序就可以避免死锁了
例:都是left - right
public void leftRight() throws InterruptedException {
// 得到left锁
synchronized (left) {
System.out.println("线程1:获得左锁");
Thread.sleep(1000);
// 得到right锁
synchronized (right) {
System.out.println("线程1:获得右锁");
}
}
}
public void rightLeft() throws InterruptedException {
// 得到right锁(改left)
synchronized (left) {
System.out.println("线程2:获得右锁");
Thread.sleep(1000);
// 得到left锁(改right)
synchronized (right) {
System.out.println("线程2:获得左锁");
}
}
}
- 动态锁顺序死锁
hash值来固定加锁的顺序
本质上也是固定加锁顺序
// 得到锁的hash值
int fromHash = System.identityHashCode(fromAcct);
int toHash = System.identityHashCode(toAcct);
// 根据hash值来上锁
if (fromHash < toHash) {
synchronized (fromAcct) {
synchronized (toAcct) {
new Helper().transfer();
}
}
} else if (fromHash > toHash) {// 根据hash值来上锁
synchronized (toAcct) {
synchronized (fromAcct) {
new Helper().transfer();
}
}
} else {// 额外的锁、避免两个对象hash值相等的情况(即使很少)
synchronized (tieLock) {
synchronized (fromAcct) {
synchronized (toAcct) {
new Helper().transfer();
}
}
}
}
开放调用避免死锁
在协作对象之间发生死锁的例子中,主要是因为在调用某个方法时就需要持有锁,并且在方法内部也调用了其他带锁的方法
开放调用:在调用某个方法时不需要持有锁
// 加Taxi内置锁
synchronized (this) {
this.location = location;
reachedDestination = location.equals(destination);
}
// 执行同步代码块后完毕,释放锁
if (reachedDestination)
// 加Dispatcher内置锁
dispatcher.notifyAvailable(this);
}
对于前面的方法内部需要调用其它锁:
// setLocation 需要Taxi内置锁
public synchronized void setLocation(Point location) {
this.location = location;
if (location.equals(destination))
// 调用notifyAvailable()需要Dispatcher内置锁
dispatcher.notifyAvailable(this);
}
public synchronized void notifyAvailable(Taxi taxi) {
availableTaxis.add(taxi);
}
定时锁
Lock锁中的tryLock()方法可以指定等待时间
当超过时间线程不等待,报错并释放线程,就可以解决死锁
死锁检测工具
JDK提供了两种方式来给我们检测:
- JconsoleJDK自带的图形化界面工具,使用JDK给我们的的工具JConsole
- Jstack是JDK自带的命令行工具,主要用于线程Dump分析