线程死锁问题

来源:互联网 发布:linux修改hosts文件 编辑:程序博客网 时间:2024/06/04 18:03

1、线程死锁的原因

死锁是指两个或两个以上的进程在执行过程中,由于竞争资源或者由于彼此通信而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁,这些永远在互相等待的进程称为死锁进程

2、举个栗子,来说明一下死锁

这里写图片描述

(1)现在有T1,T2两个线程
(2)T1需要先使用R1,然后再去请求R2
(3)T2需要先使用R2,然后再去请求R1
(4)为了是数据同步在请求的过程中都加锁来同步
(4)在T1使用R1的过程中,T2正好也在使用R2,然后T1需要请求R2才能结束,但是R2已经被T2这个线程锁住,T2需要请求R1才能结束,但是R1已经被T1锁住,两方都在等待另一方释放资源来结束自己,这就导致了死锁的现象。

3、java代码如下

    package com.smart.framework.thread;/** * Created with IntelliJ IDEA. * Description: * 段浩杰   2017-08-04-15:56 */public class TestDead implements  Runnable{    private int flage;    private static Object object1=new Object(),object2=new Object();    public TestDead(int flage) {        this.flage = flage;    }    @Override    public void run() {        if (flage==0){            synchronized (object1){                try {                    Thread.sleep(1000);                }catch (Exception e){                }                synchronized (object2){                    System.out.println("1");                }            }        }        if (flage==1){            synchronized (object2){                try {                    Thread.sleep(1000);                }catch (Exception e){                }                synchronized (object1){                    System.out.println("0");                }            }        }    }    public static void main(String args[]) {        TestDead testDead1= new TestDead(1);        TestDead testDead2= new TestDead(0);        Thread thread1=new Thread(testDead1);        Thread thread2=new Thread(testDead2);        thread1.start();        thread2.start();    }}

里面的两个资源要用static修饰,来表示是两个对象竞争的是同一资源。运行之后发现无输出,静静的在等待。

4、避免死锁
在有些情况下死锁是可以避免的。三种用于避免死锁的技术:
(1)加锁顺序(线程按照一定的顺序加锁)
(2)加锁时限(线程尝试获取锁的时候加上一定的时限,超过时限则放弃对该锁的请求,并释放自己占有的锁)
(3)死锁检测