Homework 7 2019529628047 MOHAMMED ANVAR Version 0 |
|
đ¤ Author: by wx287_oz26ft8z0hrxg4bfxzjnbg_sik8g 2022-02-17 13:40:28 |
Solution:
In this example,
public class DieLock{
public static Object t1 = new Object();
public static Object t2 = new Object();
publict static void main(String[] args) {
new Threado (){
@Override
public void run(){
synchronized(t1) {
System.out.println("Thread1 get t1");
try{
Thread.sleep(100);
}catch (Exception e)
synchronized(t2){
System.out.println("Thread2 get t2");
}
}
}
}.start()'
new Thread(){
@Override public void run(){
synchronized (t2) {
System.out.println("Thread2 get t2");
try {
Thread.sleep(100);
} catch (Exception e) {
}
synchronized (t1)
System.out.println("Thread2 get t1");
}
}
}
start();
}
}
a. I figure out from the problem that both wait for each other to release the lock they hold, and then wait until death. Likewise,
b. When it comes to avoiding deadlock; Avoid one thread acquiring multiple locks at the same time;
Avoid a thread occupying multiple resources in the lock at eh same time, and try to ensure that each lock occupies only one resource;
Try timing lock, use locktryLock(timeout) instead of using an internal locking mechanism;
Tor database lock locking, and unlocking must be in one database connection, otherwise, unlocking failure will occur.