java 多线程-死锁的产生以及解决方案

死锁:
过多的同步造成相互不释放资源,从而过多地等待,一般发生于
同步中持有多个对象的锁

snchronized锁住对象同时,另一个snchronized就不能锁该对象
避免在一个代码块中,同时持有多个对象的锁

死锁:

public class tt {

public static void main(String[]args)
{
markup m1=new markup(1,“me”);
markup m2 =new markup(2,“she”);
m1.start();
m2.start();
}
}

//口红
class lipstick{

}

//镜子
class mirror{

}

//化妆
class markup extends Thread{
//加静态表示一份,不管创建几个对象都是一份
static lipstick lip=new lipstick();
static mirror mir=new mirror();

//选择
int choice;
String girl;

public markup(int choice,String girl)
{
this.choice=choice;
this.girl=girl;
}

public void run(){

mark();

}
//相互持有对方的对象锁–>可能造成死锁
//加等待时间是为了让另一个线程锁相同对象的时候,该线程
//锁的相同对象还没有结束
//在这个死锁中,第一个线程内的mir要等第二个已经开始的mir锁结束才能执行
//而第二个线程内的mir结束需要等第一个线程内的lip解锁才行
private void mark()
{
if(choice==0)
{
synchronized(lip)
{
System.out.println(this.girl+“获得口红”);
//一秒后想要镜子
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(mir)
{
System.out.println(this.girl+“获得镜子”);
}

    }

}else
{
    synchronized(mir)
    {
        System.out.println(this.girl+"获得镜子");
        //2秒后想要口红
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    synchronized(lip)
        {
            System.out.println(this.girl+"获得口红");
        } 
    }

}

}
}
解决:

public class tt {

public static void main(String[]args)
{
markup m1=new markup(1,“me”);
markup m2 =new markup(2,“she”);
m1.start();
m2.start();
}
}

//口红
class lipstick{

}

//镜子
class mirror{

}

//化妆
class markup extends Thread{
//加静态表示一份,不管创建几个对象都是一份
static lipstick lip=new lipstick();
static mirror mir=new mirror();

//选择
int choice;
String girl;

public markup(int choice,String girl)
{
this.choice=choice;
this.girl=girl;
}

public void run(){

mark();

}
{
if(choice==0)
{
synchronized(lip)
{
System.out.println(this.girl+“获得口红”);
//一秒后想要镜子
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized(mir)
{
System.out.println(this.girl+“获得镜子”);
}

}else
{
    synchronized(mir)
    {
        System.out.println(this.girl+"获得镜子");
        //2秒后想要口红
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    synchronized(lip)
    {
        System.out.println(this.girl+"获得口红");
    } 

}

}
}
东莞网站建设www.zg886.cn

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值