加粗样式
public class sisuo implements Runnable{
int flag=1;
static Object a =new Object();//必须是静态的变量
static Object b =new Object();
public static void main(String[] args) {
sisuo si1=new sisuo();
sisuo si2=new sisuo();
si1.flag=1;
si2.flag=0;
new Thread(si1).start();
new Thread(si2).start();
}
@Override
public void run() {
System.out.println("flag="+flag);
if (flag==1){
synchronized(a){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (b){
System.out.println("1");
}
}
}
if (flag==0){
synchronized(b){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (a){
System.out.println("0");
}
}
}
}
}
思路:
1.在一个类中创建三个变量(flag、object1和object2(这两个代表着两把锁))
2.而两个线程都分别拿着对方需要的一把锁,互不谦让,导致了死锁的发生