java 中死锁_java中的死锁问题

哲学家吃面问题,下图有五个哲学家,五根筷子,如果每个人都先拿自己右手边的筷子,那大家左手边就没有筷子了。哲学家吃面问题(死锁)

看一个简单的死锁程序:

package deadlock;

import java.util.concurrent.TimeUnit;

public class ThreadDemo5

{

public static Integer r1 = 1;

public static Integer r2 = 2;

public static void main(String args[]) throws InterruptedException

{

TestThread51 t1 = new TestThread51();

t1.start();

TestThread52 t2 = new TestThread52();

t2.start();

}

}

class TestThread51 extends Thread

{

public void run()

{

//先要r1,再要r2

synchronized(ThreadDemo5.r1)

{

try {

TimeUnit.SECONDS.sleep(3);

} catch (InterruptedException e) {

e.printStackTrace();

}

synchronized(ThreadDemo5.r2) //r2被TestThread52占用

{

System.out.println("TestThread51 is running");

}

}

}

}

class TestThread52 extends Thread

{

public void run()

{

//保持同样的顺讯,先要r1,再要r2

synchronized(ThreadDemo5.r2)

try {

TimeUnit.SECONDS.sleep(3);//跟直接用thread sleep差不多

} catch (InterruptedException e) {

e.printStackTrace();

}

synchronized(ThreadDemo5.r1)//r1被TestThread51占用 造成死锁

{

System.out.println("TestThread52 is running");

}

}

}

}

解决上边死锁问题,对资源进行等级访问,(比如TestThread51和TestThread52都是先r1后r2,顺序一样就没问题了。)

如下改法就没问题了:

package deadlock;

import java.util.concurrent.TimeUnit;

public class ThreadDemo5

{

public static Integer r1 = 1;

public static Integer r2 = 2;

public static void main(String args[]) throws InterruptedException

{

TestThread51 t1 = new TestThread51();

t1.start();

TestThread52 t2 = new TestThread52();

t2.start();

}

}

class TestThread51 extends Thread

{

public void run()

{

//先要r1,再要r2

synchronized(ThreadDemo5.r1)

{

try {

TimeUnit.SECONDS.sleep(3);

} catch (InterruptedException e) {

e.printStackTrace();

}

synchronized(ThreadDemo5.r2)

{

System.out.println("TestThread51 is running");

}

}

}

}

class TestThread52 extends Thread

{

public void run()

{

//先要r2,再要r1

synchronized(ThreadDemo5.r1)

{

try {

TimeUnit.SECONDS.sleep(3);

} catch (InterruptedException e) {

e.printStackTrace();

}

synchronized(ThreadDemo5.r2)

{

System.out.println("TestThread52 is running");

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值