//利用抢占各自的资源实现线程死锁
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");
}
}
}
}
}
2025 - 快车库 - 我的知识库 重庆启连科技有限公司 渝ICP备16002641号-10
企客连连 表单助手 企服开发 榜单123