package cn.java.thread;
public class Task implements Runnable{
private boolean flag=true;
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
if(flag){
while(true)
synchronized(MyLock.locka){
System.out.println("if....locka");
synchronized(MyLock.lockb){
System.out.println("if....lockb");
}
}
}else{
while(true)
synchronized(MyLock.lockb){
System.out.println("else....lockb");
synchronized(MyLock.locka){
System.out.println("else....locka");
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Task t =new Task();
Thread t1 =new Thread(t);
Thread t2 =new Thread(t);
t1.start();
t.setFlag(false);
//让主线程放出执行资格,确保t2线程进入else循环中
Thread.sleep(10);
t2.start();
}
}
class MyLock{
public static Object locka= new Object();
public static Object lockb= new Object();
}
同步嵌套死锁例子
最新推荐文章于 2023-04-03 04:17:59 发布