欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

线程死锁例子

程序员文章站 2022-04-17 18:33:26
...

public class TestDeadLock implements Runnable{
public int flag = 1;
static Object obj1 = new Object(),obj2 = new Object();

public void run() {
System.out.println("flag= "+flag);

if(flag==1) {
synchronized (obj1) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj2) {
System.out.println("1");
}
}
}

if(flag==0) {
synchronized (obj2) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (obj1) {
System.out.println("0");
}
}
}
}
public static void main(String[] args) {
TestDeadLock td1 = new TestDeadLock();
TestDeadLock td2 = new TestDeadLock();
td1.flag = 1;
td2.flag = 0;
Thread t1 = new Thread(td1);
Thread t2 = new Thread(td2);

t1.start();
t2.start();
}
}

相关标签: thread