//利用抢占各自的资源实现线程死锁
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");
}
}
}
}
}
點(diǎn)擊查看更多內(nèi)容
2人點(diǎn)贊
評論
評論
共同學(xué)習(xí),寫下你的評論
評論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦