//利用抢占各自的资源实现线程死锁
package test;
public class DeadLock implements Runnable {
private boolean flag;
private static final Object o1 = new Object();
private static final Object o2 = new Object();
public static void main(String[] args) {
// TODO Auto-generated method stub
DeadLock d1 = new DeadLock();
DeadLock d2 = new DeadLock();
d1.flag = true;
d2.flag = false;
new Thread(d1).start();
new Thread(d2).start();
}
@Override
public void run() {
// TODO Auto-generated method stub
String threadName = Thread.currentThread().getName();
System.out.println(threadName + ":" + flag);
if (flag == true) {
synchronized (o1) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
System.out.println(threadName + "进入同步块o1准备进入2o2");
synchronized (o2) {
System.out.println(threadName + "已经进入同步块o2");
}
}
}
if (flag == false) {
synchronized (o2) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
System.out.println(threadName + " 同步块o2准备进入o1");
synchronized (o1) {
System.out.println(threadName + "已经进入同步块o1");
}
}
}
}
}
点击查看更多内容
2人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦