2019329621249陈雅冰homework7 Version 0 |
|
👤 Author: by 1422679707qqcom 2021-12-25 17:34:03 |
/**
* A simple deadlock class
* When flag==1 of the DeadLock class object (td1), lock o1 first and sleep for 500 milliseconds.
* While td1 is sleeping, another object with flag==0 (td2) thread starts, locks o2 first and sleeps for 500 milliseconds.
* td1 needs to lock o2 after sleep to continue execution, while o2 has been locked by td2;
* After TD2 sleep, it is necessary to lock o1 to continue execution, while o1 has been locked by td1;
* td1 and td2 are waiting for each other, and they all need resources locked by the other party to continue execution, which leads to deadlock.
*/
public class DeadLock implements Runnable {
public int flag = 1;
//Static objects are shared by all objects of the class.
private static Object o1 = new Object(), o2 = new Object();
@Override
public void run() {
System.out.println("flag=" + flag);
if (flag == 1) {
synchronized (o1) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (o2) {
System.out.println("1");
}
}
}
if (flag == 0) {
synchronized (o2) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (o1) {
System.out.println("0");
}
}
}
}
public static void main(String[] args) {
DeadLock td1 = new DeadLock();
DeadLock td2 = new DeadLock();
td1.flag = 1;
td2.flag = 0;
//td1 and td2 are all in executable state, but it is uncertain which thread will be executed first by JVM thread scheduling.
//td2' s run () may run before td1' s run ()
new Thread(td1).start();
new Thread(td2).start();
}
}