62,623
社区成员
发帖
与我相关
我的任务
分享
public class $03_DeadLock {
public static void main(String[] args) {
Demo demo1 = new Demo(1);
Demo demo2 = new Demo(0);
Thread t1 = new Thread(demo1);
Thread t2 = new Thread(demo2);
t1.start();
t2.start();
}
}
class Demo implements Runnable{
public int flag = 0;
static Object o1 = new Object();
static Object o2 = new Object();
Demo(int flag){
this.flag=flag;
}
public void run() {
// TODO Auto-generated method stub
System.out.println("flag="+flag);
if(flag==1){
synchronized (o1) {
System.out.println(Thread.currentThread().getName()+"持有o1的锁");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized (o2) {
System.out.println("执行完了!");
}
}
if(flag==0){
synchronized (o2) {
System.out.println(Thread.currentThread().getName()+"持有o2的锁");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized (o1) {
System.out.println("执行完了!");
}
}
}
}