线程死锁例子
程序员文章站
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();
}
}
上一篇: 线程+栈 简单实现 生产者消费者关系